DI, IOC

이지수·2022년 4월 19일
0

DI(Dpendency Injection)

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); // 의존관계를 프로그래밍으로 직접 설정한다.
}

스프링 XML을 이용한 의존 관계설정

// 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")
  }
}

스프링 XML을 이용한 의존 관계설정 @Autowired

// 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")
  }
}

ApplicationContext가 하는 일


1. 설정에 따라 Bean을 생성하고
2. 의존관계를 주입한다

profile
공부합시다

0개의 댓글