DI, IOC


DI(Dpendency Injection)


DIIとはスプリングIOC(InverseofControl)コンテナが配置に応じてbeanに注入される依存関係を指す.一般的なJavaアプリケーションがnewキーワードで生成するオブジェクトと開発者が直接依存関係を指定するのとは対照的に、SpringフレームワークはSpring IOCコンテナによって設定(xmlファイル、Annotation、BeanConfig)に従って自動的に生成され、beanが注入される.

一般的なJavaプログラムでの依存関係

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

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

Spring 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.注入依存関係