샐님 2023. 5. 21. 17:21
728x90
반응형

의존 객체 자동 주입이란?

 -스프링 설정 파일에서 의존 객체를 주입할 때 또는 태그로 의존 대상 객체를 명시하지 않아도 스프링 컨테이너 가 자동으로 필요한 의존 대상 객체를 찾아서 의존 대상 객체가 필요한 객체에 주입해 주는 기능이다. 구현 방법은

@Autowired와 @Resource 어노테이션을 이용해서 쉽게 구현할 수 있다.

@Autowired

 - 주입하려고 하는 객체의 타입이 일치하는 객체를 스프링 컨테이너 내에세 찾아 자동으로 주입한다.

 

기존 appicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
 		http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--  자동으로 객체를 생성시켜줌. 메모리에 로딩시켜줌 -->
	<!-- <bean id="cwalk" class="testprj.TranspotationWalk" /> -->
	<bean id="studentDao" class="testprj.dao.StudentDao" ></bean>
	
	
	<bean id="cregisterService" class="testprj.service.StudentRegiterService">
    <!--기존 파일에서 constructor-arg 를 사용하지 않고 생성자에 studentDao를 주입시킨다.-->
		<constructor-arg ref="studentDao" ></constructor-arg>
	</bean>
	<bean id="cSelectAllService" class="testprj.service.StudentSelectAllService">
		<constructor-arg ref="studentDao" ></constructor-arg>
	</bean>
		<bean id="cSelectService" class="testprj.service.StudentSelectService">
		<constructor-arg ref="studentDao" ></constructor-arg>
	</bean>
	

</beans>

변경후

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	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 
 		http://www.springframework.org/schema/beans/spring-beans.xsd 
 		http://www.springframework.org/schema/context 
 		http://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config />
<bean id="studentDao" class="testprj.dao.StudentDao" ></bean>
	
	
	<bean id="cregisterService" class="testprj.service.StudentRegiterService">
	</bean>
	<bean id="cSelectAllService" class="testprj.service.StudentSelectAllService">
	</bean>
		<bean id="cSelectService" class="testprj.service.StudentSelectService">
	</bean>
	

	
</beans>

Main.java 에서 바뀐 xml 을 사용한다.

 

@Resource 

@Resource란?

 - 객체의 이름과 같은 bean id 를 찾아 생성해준다.

- @Autowired 와 다르게 생성자에서는 못쓰고 프로퍼티 또는 메소드에서만 가능

 

 

#springframework #스프링프레임워크 #어노테이션 #자바 #개발자공부 #코딩 #프로그래밍 #인프런강의 #스프링강의

728x90
반응형