스프링 컨테이너는 다양한 형식의 설정 정보를 받아드릴 수 있게 설계되었다.
애노테이션 기반 자바 코드 설정 사용
AnnotationConfig는 현재 사용해본 방식이다.
new AnnotationConfigApplicationContext(AppConfig.class);
이 클래스를 사용하면서 자바 코드로된 설정 정보를 넘기면 되낟.
XML 설정 사용
최근에는 스프링 부트를 많이 사용하면서 XML기반의 설정은 잘 사용하지 않지만
아직 남아있는 곳들도 있다. XML은 컴파일 없이 설정 정보를 변경할 수 있는 장점도 있으므로
알아보았다.
GenericXMLApplicationContext를 사용하면서 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="hello.core.member.MemberServiceImpl">
<constructor-arg name="memberRepository" ref="memberRepository" />
</bean>
<bean id="memberRepository" class="hello.core.member.MemoryMemberRepository" />
<bean id="orderService" class="hello.core.order.OrderServiceImpl">
<constructor-arg name="memberRepository" ref="memberRepository" />
<constructor-arg name="discountPolicy" ref="discountPolicy" />
</bean>
<bean id="discountPolicy" class="hello.core.discount.RateDiscountPolicy" />
</beans>
xml 기반의 설정 정보는 AppConfig.java와 거의 동일하다!
package hello.core.xml;
import hello.core.member.MemberService;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import static org.assertj.core.api.Assertions.*;
public class XmlAppContext {
@Test
void xmlAppContext(){
ApplicationContext ac = new GenericXmlApplicationContext("appConfig.xml");
MemberService memberService = ac.getBean("memberService", MemberService.class);
assertThat(memberService).isInstanceOf(MemberService.class) ;
}
}
테스트 코드로 실행시켜 보았더니 Singleton Bean이라는 문구와 함께
객체 이름이 반환되었다.
'웹프로그래밍 > Spring 핵심 원리' 카테고리의 다른 글
26. 웹 애플리케이션과 싱글톤 (0) | 2021.07.22 |
---|---|
25. 스프링 빈 설정 메타 정보 - BeanDefinition (0) | 2021.07.21 |
23. BeanFactory와 ApplicationContext (0) | 2021.07.20 |
22. 스프링 빈 조회 - 상속관계 (0) | 2021.07.20 |
21. 스프링 빈 조회 - 동일한 타입이 둘 이상 (0) | 2021.07.19 |