본문 바로가기

[Spring]

[Spring]11월 9일 스프링 설정 파일을 이용한 객체간의 의존관계 설정


http://smjava.tistory.com/61 내용에 이어서 스프링 설정 파일을 이용한 객체간의 의존관계 설정을 해보겠습니다.


di5번 패키지를 생성합니다.

di2번 패키지 내용을 복사 붙혀놓기 해서 main함수에서 직접 커피의 온도를 지정하고, 커피에 넣어주던 과정을 스프링 설정 파일을 통해 미리 작업해보자.

우선 di5 패키지에 스프링 설정 파일을 만들자.

di2 패키지는 생성자 주입 버전으로 만든 패키지였습니다. 잘 모르시겠으면 위에 링크주소가셔서 다시 참고하세요!


di5 스프링 설정파일

<?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="hot" class="di5.HotAmericano"></bean>

<bean id="ice" class="di5.IceAmericano"></bean>

<bean id="c" class="di5.Coffee">

<constructor-arg ref="ice"></constructor-arg>

</bean>


</beans>

저는 둘다 소환해놓고 ice로 넣어준거에요~


<constructor-arg ref="ice"></constructor-arg>

요거는 생성자의 매개변수에 ice라는 빈(bean)객체를 넣겠다.

속성으로는 

어디에 : name , index

무엇을 : ref , value

ref는 참조값, 객체(bean)를 넣을때

value는 상수를 넣을때


위에서 name을 안사용한 이유는 name 속성은 두개이상의 같은 타입의 매개변수가 있을때만 써주자!


설정파일을 만들었으니 스프링 컨테이너에서 불러봐야겟죠

package di5;


import org.springframework.context.ApplicationContext;

import org.springframework.context.support.GenericXmlApplicationContext;


public class Test {

public static void main(String[] args){

ApplicationContext context = new GenericXmlApplicationContext("di5/applicationContext.xml");

Coffee c = context.getBean("c" , Coffee.class);

c.coffeeType();

}

}



이제 그다음으로는 di6 패키지 생성합니다

di6번 에서는 스프링기반 설정자를 이용한 주입을 해볼거니까

설정자주입 방법으로 작성해놓은 di3번 패키지를 복사해서 가져옵니다.


di6 스프링 설정파일

<?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="hot" class="di6.HotAmericano"></bean>

<bean id="ice" class="di6.IceAmericano"></bean>

<bean id="c" class="di6.Coffee">

<property name="coffee" ref="ice"></property>

</bean>

</beans>


일단 Coffee , IceAmericano, HotAmericano 세개의 빈객체를 등록하시고,


<property name="coffee" ref="ice"></property> 여기서 name은 우리가 커피클래스에 setter를 만들어 놓았으므로 자동완성이 된다.

set으로 시작하는 함수들이 전부 set떼고 첫글자 소문자로 바뀌어서 나온다.

객체를 만들거나 객체간에 객체를 주입시켜주는 작업은 스프링 컨테이너에서 모두 완료 했으니, 자바 코드상에서는 필요한 기능을 호출해서 사용만 하면된다.


package di6;


import org.springframework.context.ApplicationContext;

import org.springframework.context.support.GenericXmlApplicationContext;


public class Test {

public static void main(String[] args){

ApplicationContext context = new GenericXmlApplicationContext("di6/applicationContext.xml");

Coffee c = context.getBean("c", Coffee.class);

c.coffeeType();

}

}



출처 : 삼성SDS멀티캠퍼스

강사 : 홍승길

Email : iccack70@gmail.com