스프링Spring
[Spring] 스프링 자동주입
개린이9999
2023. 1. 17. 06:53
728x90
Bean을 정의할 때 주입할 객체는 생성자를 통한 주입이나 setter를 통한 주입을 사용했다.
Spring에서는 객체를 주입할 때 자동으로 주입될 수 있도록 설정이 가능하다.
자동 주입은 이름, 타입, 생성자를 통할 수 있으며 auto wire라는 용어로 부른다.
이름을통한주입
byName: 빈 객체의 property 이름과 정의된 Bean의 이름이 같은 것을 찾아 자동으로 주입함.
<?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='obj1' class='sanghoon.beans.TestBean1'>
<property name="data1" ref='data_bean1'/>
<property name="data2" ref='data_bean1'/>
</bean>
<bean id='data_bean1' class='sanghoon.beans.DataBean1' scope='prototype'/>
<bean id='obj2' class='sanghoon.beans.TestBean1' autowire="byName"/>
<bean id='data1' class='sanghoon.beans.DataBean1'/>
<bean id='data2' class='sanghoon.beans.DataBean1'/>
</beans>
package sanghoon.main;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sanghoon.beans.TestBean1;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("sanghoon/config/beans.xml");
TestBean1 obj1 =ctx.getBean("obj1",TestBean1.class);
System.out.printf("obj1.data1:%s\n" , obj1.getData1());
System.out.printf("obj1.data2:%s\n" , obj1.getData2());
System.out.println("-----------------------");
TestBean1 obj2 = ctx.getBean("obj2",TestBean1.class);
System.out.printf("obj2.data1:%s\n" , obj1.getData1());
System.out.printf("obj2.data2:%s\n" , obj1.getData2());
ctx.close();
}
}
autowire에 bytype 이면 class타입으로 주입, constructor면 생성자로 주입
728x90