티스토리 뷰
다양한 설정 형식 지원 - 자바 코드, XML
스프링 컨테이너는 다양한 형식의 설정 정보를 받아드릴 수 있게 유연하게 설계되어 있다.
ex) 자바 코드, XML, Groovy 등
구조도
1. 애노테이션 기반 자바 코드 설정 사용
- 지금까지 했던 것
- new AnnotationConfigApplicationContext(AppConfig.class)
- `AnnotationConfigApplicationContext` 클래스를 사용하면서 자바 코드로된 설정 정보를 넘기면 된다.
2. XML 설정 사용
- 최근에는 스프링 부트를 많이 사용하면서 XML기반의 설정은 잘 사용하지 않는다. 아직 많은 레거시 프로젝트 들이 XML로 되어 있고, 또 XML을 사용하면 컴파일 없이 빈 설정 정보를 변경할 수 있는 장점도 있으므로 한번쯤 배워두는 것도 괜찮다.
- `GenericXmlApplicationContext` 를 사용하면서 `xml` 설정 파일을 넘기면 된다.
XmlAppConfig 사용 자바 코드
public class XmlAppContext {
@Test
void xmlAppContext() {
ApplicationContext ac = new GenericXmlApplicationContext("appConfig.xml");
MemberService memberService = ac.getBean("memberService", MemberService.class);
assertThat(memberService).isInstanceOf(MemberService.class);
}
}
xml 기반의 스프링 빈 설정 정보
src/main/resources/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">
<!-- memberService 빈 설정 -->
<bean id="memberService" class="inflearn.spring_core.member.MemberServiceImpl">
<!-- memberService 빈의 생성자에 memberRepository 빈을 주입 -->
<constructor-arg name="memberRepository" ref="memberRepository" />
</bean>
<!-- memberRepository 빈 설정 -->
<bean id="memberRepository" class="inflearn.spring_core.member.MemoryMemberRepository" />
<!-- orderService 빈 설정 -->
<bean id="orderService" class="inflearn.spring_core.order.OrderServiceImpl">
<!-- orderService 빈의 생성자에 memberRepository와 discountPolicy 빈을 주입 -->
<constructor-arg name="memberRepository" ref="memberRepository" />
<constructor-arg name="discountPolicy" ref="discountPolicy" />
</bean>
<!-- discountPolicy 빈 설정 -->
<bean id="discountPolicy" class="inflearn.spring_core.discount.RateDiscountPolicy" />
</beans>
- xml 기반의 `appConfig.xml` 스프링 설정 정보와 자바 코드로 된 `AppConfig.java` 설정 정보를 비교해보면
거의 비슷하다는 것을 알 수 있다. - xml 기반으로 설정하는 것은 최근에 잘 사용하지 않으므로 이정도로 마무리 하고, 필요하면 스프링 공식 레퍼런스
문서를 확인하자.
https://spring.io/projects/spring-framework
728x90
반응형
'[개발] - Spring > 핵심 원리 구현' 카테고리의 다른 글
웹 애플리케이션과 싱글톤 (0) | 2024.01.25 |
---|---|
스프링 빈 설정 메타 정보 - BeanDefinition (0) | 2024.01.24 |
BeanFactory와 ApplicationContext (0) | 2024.01.23 |
스프링 빈 조회 (2) 상속 관계 (1) | 2024.01.22 |
스프링 빈 조회 (1) - 기본 / 동일한 타입이 둘 이상인 경우 (0) | 2024.01.22 |
Comments