DI란 스프링 IOC(Inverse of Control) 컨테이너가 Bean의 의존관계를 설정에 따라서 주입하는 일을 말한다. 일반적인 자바 어플리케이션이 new
키워드를 통해서 객체를 생성하고 의존관계를 개발자가 직접 지정하는데 반해서, 스프링 프레임워크는 스프링 IOC 컨테이너가 설정에 (xml파일, Annotation, BeanConfig) 따라 자동으로 Bean을 생성하고 주입하는 역할을 한다.
class Student {
String name;
public Student(String name) {
this.name = name;
}
}
class School {
private Student student;
public setStudent (Student student) {
this.student = student;
}
}
public void main(String[] args) {
new School school = new School();
new Student student1 = new Student("이지수")
school.setStudent(student1); // 의존관계를 프로그래밍으로 직접 설정한다.
}
// test-application.xml
<beans>
<bean id="school" class="com.abc.School">
<property name="student" ref="student" />
</bean>
<bean id="student" class="com.abc.Student">
<constructor-arg type="java.lang.String" value="이지수"/>
</bean>
</beans>
// java application
public void main(String[] args) {
ApplicationContext context
= new ClassPathXmlApplicationContext("classpath:spring/test-application.xml");
School school = (School)context.getBean("school");
Student student = (Student)context.getBean("student");
Student student2 = school.getStudent();
if (student == student2) {
System.out.println("OK")
}
}
// test-application.xml
<beans>
<bean id="school" class="com.abc.School"/>
<bean id="student" class="com.abc.Student"/>
</beans>
class Student {
String name;
@Autowired // xml 에서는 의존관계가 제거되고, Autowired 키워드가 여기 붙었다.
public Student(String name) {
this.name = name;
}
}
class School {
private Student student;
public setStudent (Student student) {
this.student = student;
}
}
// java application
public void main(String[] args) {
ApplicationContext context
= new ClassPathXmlApplicationContext("classpath:spring/test-application.xml");
School school = (School)context.getBean("school");
Student student = (Student)context.getBean("student");
Student student2 = school.getStudent();
if (student == student2) {
System.out.println("OK")
}
}
1. 설정에 따라 Bean을 생성하고
2. 의존관계를 주입한다