본문으로 바로가기

[스프링]5. @Autowired// @Component 어노테이션 사용

category SPRING/스프링 2021. 3. 30. 14:41
728x90
반응형
SMALL

클래스 파일 내에서 @Autowired 를 선언해줌 으로서 불필요한 xml 설정을 대체할 수 있게 된다.

예제를 보자

xml 파일

현재 

ListController 클래스 내에서 noticeService 클래스 를 쓰기 위해 xml에 주입이 설정된 상태이다.

저 구문에서 해당 내용을 주석처리하여 지운후

<!-- <property name="noticeService" ref="noticeService" /> -->

 

ListController 내에서 @Autowired 어노테이션을 선언만 해주면 똑같이 사용할 수 있게된다.

이 얼마나 간편한가!!

 

db접속을 위한 xml 설정도 또한 마찬가지로 적용시키면

이 구문을 주석처리 해주고 해당 구문을 사용하는 클래스로 가서

어노테이션 처리만 해주자.

 

이런식으로 setter만 어노테이션 처리하여 이용할 수 있으며 클래스 파일 전체를 어노테이션으로 대체할 수도 있다.

xml 파일

noticeService 클래스가 주입이 설정된 xml 구문을 주석처리하여 지운후 해당 구문을 추가해주자

<context:component-scan base-package="com.newlecture.web.service"></context:component-scan>

Component 어노테이션을 사용하여 클래스 파일을 객체로 만들어 쓸수있으며 해당 클래스 파일을 포함하는 패키지를 경로를 스캔한다.

출처:뉴렉처님의 유튜브

 

이후 해당 클래스로 가서 @Service 어노테이션(@Component와 같음)을 선언해줌으로서 xml 설정을 대체할수 있게된다.

 

전체xml 파일

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 	xmlns:mvc="http://www.springframework.org/schema/mvc"
 	xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
        
    <!-- 어노테이션을 쓰기위한 설정 -->    
    <!-- <context:annotation-config />   --> 
    <!-- Component 어노테이션을 써서 클래스 파일을 객체로 만들어 쓰기 위해서 스캔으로  찾아서 쓴다 
    <context:annotation-config />기능 또한 스캔 안에 있기 때문에 선언 안해줘도된다.
    -->
	<context:component-scan base-package="com.newlecture.web.service"></context:component-scan>
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"
			value="oracle.jdbc.driver.OracleDriver" />
		<property name="url"
			value="jdbc:oracle:thin:@localhost:1521/XE" />
		<property name="username" value="newlec" />
		<property name="password" value="11111" />

	</bean>


	<!-- <bean id="noticeService"
		class="com.newlecture.web.service.jdbc.JDBCNoticeService">
		<property name="dataSource" ref="dataSource"/>
	</bean> -->

  
</beans>
728x90
반응형
LIST