본 게시물은 김영한 선생님의 강의를 학습하며 작성하였습니다.
- 스프링 컨테이너는 다양한 형식의 설정 정보를 받아드릴 수 있게 유연하게 설계되어 있다.
- 자보바 코드, XML, Groovy 등등
애노테이션 기반 자바 코드 설정 사용
지금까지 했던 것이다.
new AnnotationCOnfigApplicationContext(AppConfig.class)
AnnotationConfigApplicationContext
클래스를 사용하면서 자바 코드로 된 설정 정보를 넘기면 된다.
XML 설정 사용
- 최근에는 스프링 부트를 많이 사용하면서 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="com.hello.core.member.MemberServiceImpl">
<constructor-arg name="memberRepository" ref="memberRepository"/>
</bean>
<bean id="memberRepository" class="com.hello.core.member.MemoryMemberRepository"/>
<bean id="orderService" class="com.hello.core.order.OrderServiceImpl">
<constructor-arg name="memberRepository" ref="memberRepository"/>
<constructor-arg name="discountPolicy" ref="discountPolicy"/>
</bean>
<bean id="discountPolicy" class="com.hello.core.discount.RateDiscountPolicy"/>
</beans>
package com.hello.core.xml;
import com.hello.core.member.MemberService;
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);
}
}
'Backend > Spring' 카테고리의 다른 글
[섹션 5] @Configuation과 싱글톤 (0) | 2024.03.18 |
---|---|
[섹션 4] 스프링 빈 설정 메타 정보 - BeanDefinition (0) | 2024.03.18 |
[섹션 4] BeanFactory와 ApplicationContext (0) | 2024.03.18 |
[섹션 4] 스프링 빈 조회 - 상속관계 (0) | 2024.03.18 |
[섹션 4] 스프링 컨테이너와 스프링 빈 (0) | 2024.03.18 |