ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [SPRING] Day1 (Class04. 의존성 주입)
    SPRING 2021. 7. 25. 17:10

    Dependency Injection(의존성 주입) = 객체 주입

    ① 생성자 주입

    ② Setter 주입

     

    * 의존성 관계

    하나의 객체에서 다른 객체의 변수나 메소드를 이용해야 한다면 이용하려는 객체에 대한 객체 생성과 생성된 객체의 레퍼런스 정보가 필요하다.

     

    그런데 만약 의존 관계에 있는 객체에 직접 다른 객체 생성 코드를 명시한다면,

    객체 생성이 두 번이나 이루어지고, 다른 객체로 변경하려고 할 때 메소드를 모두 수정해야 하는 불편함이 생긴다.

     

    이 문제를 의존성 주입으로 해결할 수 있다.

     

     

    1. 생성자 인젝션 

     

    스프링 컨테이너는 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"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    
    <bean id="tv" class="polymorphism.SamsungTV">
    <constructor-arg ref="sony"></constructor-arg>
    </bean>
    
    <bean id="sony" class="polymorphism.SonySpeaker"></bean>
    
    </beans>

    constructor-arg 태그로 생성자 매개변수를 전달할 수 있다.

    ref 속성으로 참조하는 객체를 전달이 가능하다.

    위에서는 SonySpeaker 클래스를 sony라는 id를 가진 객체로 생성하여

    tv라는 id의 객체의 매개변수로 참조하여 전달하고 있다.

    package polymorphism;
    
    public class SamsungTV implements TV{
    	private SonySpeaker speaker;
    	
    	public SamsungTV() {
    		System.out.println("samsung 객체 생성");
    	}
    
    	public SamsungTV(SonySpeaker speaker) {
    		System.out.println("samsung(2) 객체 생성");
    		this.speaker=speaker;
    	}
    	
    	public void powerOn() {
    		System.out.println("SamsungTV---전원 켠다");
    	}
    	public void powerOff() {
    		System.out.println("SamsungTV---전원 끈다");
    	}
    	public void volumeUp() {
    		speaker.volumeUp();
    	}
    	public void volumeDown() {
    		speaker.volumeDown();
    	}
    }

    그럼 기본 생성자가 아닌 SonySpeaker를 매개변수로 받는 생성자를 호출하게 된다.

     

     

     

    2. 다중 변수 매핑

    <?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="tv" class="polymorphism.SamsungTV">
    <constructor-arg ref="sony"></constructor-arg>
    <constructor-arg value="2700000"></constructor-arg>
    </bean>
    
    <bean id="sony" class="polymorphism.SonySpeaker"></bean>
    
    </beans>

    매개변수를 넘길 때는 여러 개를 넘길 수 있다.

    bean으로 등록된 다른 객체를 매개변수로 넘길 때는 ref 속성을 사용하지만,

    기본형 데이터를 넘길 때는 value 속성을 사용한다.

     

    이렇게 인터페이스를 사용하고 xml파일을 사용하여 의존성 주입을 시켜주면 

    main 클래스에서는 더이상의 소스 수정이 이루어지지 않고 필요할 때마다 xml 설정파일에서만 변경을 해주면 된다.

    이렇게 소스 의존성을 떨어뜨릴 수 있는 것이다.

     

     

     

    3. Setter 인젝션

     

    package polymorphism;
    
    public class SamsungTV implements TV{
    	private Speaker speaker;
    	private int price;
    	
    	public SamsungTV() {
    		System.out.println("samsung 객체 생성");
    	}
    	//setter 추가
    	public void setSpeaker(Speaker speaker) {
    		System.out.println("setSpeaker 호출");
    		this.speaker=speaker;
    	}
    	//setter 추가
    	public void setPrice(int price) {
    		System.out.println("setPrice");
    		this.price=price;
    	}
    	
    	public void powerOn() {
    		System.out.println("SamsungTV---전원 켠다 (가격 : "+price+")");
    	}
    	public void powerOff() {
    		System.out.println("SamsungTV---전원 끈다");
    	}
    	public void volumeUp() {
    		speaker.volumeUp();
    	}
    	public void volumeDown() {
    		speaker.volumeDown();
    	}
    }

    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="tv" class="polymorphism.SamsungTV">
    <property name="speaker" ref="apple"></property>
    <property name="price" value="2700000"></property>
    </bean>
    
    <bean id="sony" class="polymorphism.SonySpeaker"></bean>
    <bean id="apple" class="polymorphism.AppleSpeaker"></bean>
    </beans>

    <property> 태그를 이용하여 객체를 주입한다.

    이때 name 속성은 함수명이 된다.

    즉 property 태그와 name 값은 Set[name 값]=setter 메소드가 되는 것이다.

     

     

     

    4. p 네임스페이스 이용하기

    <?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:p="http://www.springframework.org/schema/p"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="tv" class="polymorphism.SamsungTV" p:speaker-ref="sony" p:price="2700000">
    </bean>
    
    <bean id="sony" class="polymorphism.SonySpeaker"></bean>
    <bean id="apple" class="polymorphism.AppleSpeaker"></bean>
    </beans>

    p 네임스페이스를 이용하면 더 편하게 의존성 주입이 가능하다.

    p:변수명-ref="참조할 객체의 이름이나 아이디"

    p:변수명="설정할 값"

     

Designed by Tistory.