본문 바로가기

Java/Spring

DI(Dependency Injection)

DI를 왜 쓰는가? 

규모가 커진 프로젝트에 DI를 사용하여 객체간 결합도를 낮춰 유지보수를 원활하게 함.

위 예제는 인터페이스를 활용하여 스프링 설정파일(xml)만을 수정하고 Java파일을 건드리지 않으면서 수정했음.




DI 설정 1 - XML 사용

1-1. 생성자
<constructor-arg> 태그 사용

<bean id="student1" class="com.javalec.ex.Student">
          <constructor-arg value="홍길동" />



1-2. setter
<property> 태그 사용

<bean id="student1" class="com.javalec.ex.Student">
    <property name="height">
          <value>187</value>
    </property>

1-3. 축약
c:field 혹은 p:field=""


이렇게 선언하면
<beans xmlns="http://www.springframework.org/schema/beans";
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
     xmlns:c="http://www.springframework.org/schema/c";
     xmlns:p="http://www.springframework.org/schema/p";
     xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd";>



이렇게 줄여서 가능하다
     <bean id="family" class="com.javalec.ex.Family" c:papaName="홍아빠" c:mamiName="홈엄마" p:sisterName="홍누나">
          <property name="brotherName" value="홍오빠" />
     </bean>








DI 설정 2 - 자바 클래스파일 사용

package com.javalec.ex;
import java.util.ArrayList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//이걸 어노테이션이라고 해.
@Configuration
public class ApplicationConfig {
     @Bean
     public Student student1() {
          ArrayList<String> hobbys = new ArrayList<String>();
          hobbys.add("수영");
          hobbys.add("요리");
          
          Student student = new Student("홍성은",28,hobbys);
          student.setWeight(68);
          student.setHeight(172);
          
          return student;
     }
     
     @Bean
     public Student student2() {
          ArrayList<String> hobbys = new ArrayList<String>();
          hobbys.add("공부");
          hobbys.add("독서");
          
          Student student = new Student("홍성민",26,hobbys);
          student.setWeight(58);
          student.setHeight(168);
          
          return student;
     } 
}
public class MainClass {
     public static void main(String[] args) {
          
          AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
          
          Student student1 = ctx.getBean("student1", Student.class);
          System.out.println("이름 : " + student1.getName());
          
          Student student2 = ctx.getBean("student2", Student.class);
          System.out.println("이름 : " + student2.getName());
          
          ctx.close();
     }
}

DI 설정 3 - JAVA in 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";
     xmlns:context="http://www.springframework.org/schema/context";
     xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd";>
     
     <context:annotation-config />
     <bean class="com.javalec.ex.ApplicationConfig" />
     
     <bean id="student2" class="com.javalec.ex.Student">
          <constructor-arg value="홍길순"></constructor-arg>
          <constructor-arg value="30"></constructor-arg>
          <constructor-arg >
              <list>
                   <value>마라톤</value>
                   <value>요리</value>
              </list>
          </constructor-arg>
          <property name="height" value="190" />
          <property name="weight" value="70" />
     </bean>
</beans>
 public static void main(String[] args) {
              
              AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
              Student student1 = ctx.getBean("student1", Student.class);
              System.out.println("이름 : " + student1.getName());


DI 설정 4 - XML in JAVA

@Configuration
@ImportResource("classpath:applicationCTX.xml")
public class ApplicationConfig {
     @Bean
     public Student student1(){
          
          ArrayList<String> hobbys = new ArrayList<String>();
          hobbys.add("수영");
          hobbys.add("요리");
          
          Student student = new Student("홍길동", 20, hobbys);
          student.setHeight(180);
          student.setWeight(80);
          
          return student;
     }
}

public static void main(String[] args) {
              
              AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
              
              Student student1 = ctx.getBean("student1", Student.class);
              System.out.println("이름 : " + student1.getName());