본문 바로가기
Java/Spring

Spring) xml을 통한 context 작성 - DI 특징 파악하기

by 박채니 2022. 8. 12.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


DI 특징 파악하기

 

setter를 이용한 의존주입 DI

Tv interface

public interface Tv {
	void powerOn();
	
	void channelTo(int no);
}

 

LgTv

public class LgTv implements Tv {
	private RemoteControl remocon;
	
	public LgTv() {
		System.out.println("LgTv 객체 생성!");
	}
	
	/**
	 * setter를 이용한 의존주입 DI 
	 */
	public void setRemocon(RemoteControl remocon) {
		System.out.println("LgTv#setRemocon 호출! " + remocon);
		this.remocon = remocon;
	}
	
	public void channelTo(int no) {
		remocon.channelTo(no);
	}
	
	public void powerOn() {
		System.out.println("LgTv Power On!");
	}

}

 

RemoteControl interface

public interface RemoteControl {
	void channelTo(int no);
}

 

DaisoRemocon

public class DaisoRemocon implements RemoteControl {

	public void channelTo(int no) {
		System.out.println("채널을 " + no + "번으로 변경합니다.");
	}

}

 

tv-context.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="daisoRemocon" class="com.ce.spring.tv.DaisoRemocon"></bean>
	<!-- 
		scope
			- singletone (기본값)
			- prototype : getBean 요청 시마다 객체 생성
			- request : request마다 객체 생성
			- session : session마다 객체 생성
	 -->
	<bean id="lgTv" class="com.ce.spring.tv.LgTv">
		<property name="remocon" ref="daisoRemocon"></property>
	</bean>
</beans>

setter를 이용한 의존 주입으로 <property> 태그를 이용하여 setter에 주입해주었습니다.

name 속성에는 "setRemocon"에서 "set"을 제외한 "remocon"을 기입해주고, ref에는 주입받을 bean의 id값을 기입해줍니다.

주입받을 bean 역시 bean으로 등록이 되어있어야 하기 때문에 DaisoRemocon도 bean으로 등록해주었습니다.

 

TvMain

public class TvMain {

	public static void main(String[] args) {
		String configLocation = "classpath:tv-context.xml";
		ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
		System.out.println("=================== spring container 초기화 완료 ===================");
		
		Tv lgTv = (Tv) context.getBean("lgTv");	// id값으로 가져오기 (Object 반환하므로 다운캐스팅 필요)
		lgTv.powerOn();
		
		Tv lgTv2 = context.getBean(LgTv.class);	// class객체로 가져오기
		lgTv2.powerOn();
		
		lgTv.channelTo(10);
	}
}

@콘솔출력값
LgTv 객체 생성!
LgTv#setRemocon 호출! com.ce.spring.tv.DaisoRemocon@6d4b1c02
=================== spring container 초기화 완료 ===================
LgTv Power On!
LgTv Power On!
채널을 10번으로 변경합니다.

그 결과, 객체가 생성될 때 setRemocon()에 daisoRemocon이 주입이 된 것을 확인할 수 있습니다.

 


생성자를 이용한 의존주입 DI

SamsungTv

public class SamsungTv implements Tv {
	private RemoteControl remocon;
	
	public SamsungTv() {
		System.out.println("SamsungTv 객체 생성!");
	}
	
	/**
	 * 생성자를 이용한 의존주입 DI
	 */
	public SamsungTv(RemoteControl remocon) {
		System.out.println("SamsunTv 객체 생성! : " + remocon);
		this.remocon = remocon;
	}
	
	public void powerOn() {
		System.out.println("SamsungTv Power On!");
	}
	
	public void channelTo(int no) {
		remocon.channelTo(no);
	}
}

 

tv-context.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="daisoRemocon" class="com.ce.spring.tv.DaisoRemocon"></bean>
    
	<bean id="samsungTv" class="com.ce.spring.tv.SamsungTv" lazy-init="true">
		<constructor-arg ref="daisoRemocon" index="0"/> <!-- 인자가 여러개인 경우, index 이용 -->
	</bean>
</beans>

<constructor-arg>태그를 이용하여 RemoteControl를 매개인자로 받는 생성자를 만들어주었습니다.

이 역시 ref에 주입하고자 하는 bean의 id값을 기입해주며, index를 이용하여 인자가 여러개인 경우 지정해줄 수 있습니다.

 

TvMain

public class TvMain {

	public static void main(String[] args) {
		String configLocation = "classpath:tv-context.xml";
		ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
		System.out.println("=================== spring container 초기화 완료 ===================");

		SamsungTv samsungTv = context.getBean(SamsungTv.class);
		System.out.println(samsungTv);
		samsungTv.channelTo(10);
	}
}

@콘솔출력값
=================== spring container 초기화 완료 ===================
SamsunTv 객체 생성! : com.ce.spring.tv.DaisoRemocon@4667ae56
com.ce.spring.tv.SamsungTv@52a86356
채널을 10번으로 변경합니다.

 


Spring Explorer

관계들을 쉽게 파악할 수 있습니다.