Choi의 고유결계

Spring - DI(Dependency Injection) 본문

Spring

Spring - DI(Dependency Injection)

믿을수없는맛 2019. 2. 24. 17:56
반응형

DI(Dependency injection)란?

Dependency : (특히 비정상적이거나 불필요할 정도의) 의존, 종속, (다른 나라에 종속된) 속국

injection : 주사, (상황·사업 등의 개선을 위한 거액의) 자금 투입, (액체의) 주입

한마디로 말하면 의존 주입이다.

DI는 스프링만의 기능이 아니라 OOP프로그래밍을 하는 하나의 방법론으로

스프링이 그것을 채용을 하여 스프링에서 사용하고있다는 것이다.

자바 프로그래밍을 하다보면 여러번 접해봤을것이다. 어떤 객체가 필요한 객체에다가 setter나 생성자를 통해 생성할때 외부적으로 객체를 주입 하게 되어 그 주입된 객체를 사용하는것이다.

예를 들자면 장난감이 있다.
장난감은 배터리가 들어가야 동작한다.

이 장난감에다가 베터리를 넣어주면 장난감이 배터리를 소모하여 동작을 하게된다.

class battery{
    int size = 100;

}
class toy{
    battery bat;

    toy(battery bat){
        this.bat = bat;
    }

    public void setBattery(battery bat;){
        this.bat = bat;
    }
}

클래스 toy는 장난감으로 만들때부터 배터리를 하나 넣어주고,

나중에 배터리가 떨어진다면 setBattery()를 통해 배터리를 바꿔줄수있다.

class child{
    battery bat = new battery();
    battery newbat = new battery();
    toy t = new toy(bat);

    t.setBattery(newbat); 

}

이렇게 child에서는 배터리가 나중에 떨어지면 다시교체 할수 있게되는것이다.

아무튼 배터리를 생성하고 주입하는 역할을 스프링의 스프링 컨테이너가 수행하는 것이다.


스프링에서 사용하는 방법

스프링 컨테이너를 이용해서 주입하는것이기 때문에 new 키워드를 사용하여 객체 생성및 직접 주입할 필요가 없기 때문에 다른 방법으로 생성하고 주입해야한다.

스프링 컨테이너를 생성하기위한 설정파일을 만드는 방법에는 2가지가 있는데,

하나는 xml 을통해 주입하는것, 나머지 하나는 annotaion

이번 시간에는 xml을 통해서 적용하는 방법을 알아보도록 하자.

spring-context.xml에 작성하도록한다

1.생성자를 통해서 주입하는 방법

<?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="bat" class="battery"/>

  <!-- 생성자를통한 주입-->
    <bean id="carToy" class="toy">
        <constructor-arg ref="helloDAO" />
    </bean>

</beans>

2.setter를 이용하여 주입하는 방법

<?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="bat" class="battery"/>

  <!-- 생성자를통한 주입-->
    <bean id="carToy" class="toy">
    <!--프로퍼티 이름은 세터함수에서 set을 빼고 적으면된다.-->
        <property name="Battery" ref="bat"></property>
    </bean>

</beans>

child 클래스에서 toy 객체를 얻는 방법

public class child {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml");


        toy service = ctx.getBean("carToy", toy.class);
    }

}

AbstractApplicationContext생성자 매개변수로 설정해준 xml의 경로를 적어주게되면 스프링에서 알아서 배터리가 주입된 객체를 반환하게 된다.

이렇게 되면 맨위에 원래 우리가 알던 방법으로 작성한 것과 스프링컨테이너를 이용해서 만든것과 차이가 없다.


공부용으로 적은거라 내용이 보기 힘들거나 틀릴수도있습니다. 혹시라도 틀린점이 있다면 댓글로 지적해주세요. 감사합니다.


반응형
Comments