[Spring] GenericXmlApplicationContext

노유성·2023년 7월 13일
0
post-thumbnail

스프링 컨테이너의 설정 정보


스프링 컨테이너는 다양한 형시그이 설정 정보를 받아드릴 수 있게 설계되어있다. 지금까지는 우리는 annotation 기반의 코드 설정 정보를 사용한 것이고 xml을 사용할 수도 있다. 최근에는 대부분 annotaion 기반으로 사용하지만 과거 legacy 프로젝트들을 xml을 활용하고 있다. 또 xml을 사용하면 컴파일 없이 빈 설정 정보를 변경할 수 있는 장점도 있다.

appConfig.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="memberService" class="hello2.demo.member.service.MemberServiceImpl">
        <constructor-arg name="memberRepository" ref="memberRepository"/>
    </bean>
    <bean id="memberRepository" class="hello2.demo.member.repository.MemoryMemberRepository"/>
    <bean id="orderService" class="hello2.demo.order.OrderServiceImpl">
        <constructor-arg name="memberRepository" ref="memberRepository"/>
        <constructor-arg name="discountPolicy" ref="discountPolicy"/>
    </bean>
    <bean id="discountPolicy" class="hello2.demo.discount.policy.RateDiscountPolicy"/>
</beans>

참고로 java 파일이 아닌 모든 파일들을 /src/main/resource 안에다가 저장한다.

xml를 이용해서 설정 정보를 구성할 때는 class명을 패키지까지 다 적어서 저장해야 하며 constructor-arg 태그를 이용해서 의존관계를 설정할 수 있다. 자세히 들여보다면 @Configuration에서 정의한 것과 별반 다르지 않다.

Test

@Test
void xmlAppContext() {
    ApplicationContext ac 
    	= new GenericXmlApplicationContext("appConfig.xml");
    MemberService memberService 
    	= ac.getBean("memberService", MemberService.class);
    Assertions.assertThat(memberService).isInstanceOf(MemberService.class);
}

구체 class를 변경하고 설정 정보에 xml파일을 넣어주는 것 외에는 구현체를 불러오고나서부터 동일하다.

profile
풀스택개발자가되고싶습니다:)

0개의 댓글