new AnnotationConfigApplicationContext(AppConfig.class)
로 컨테이너 생성
여기서는 AppConfig.class
로 구성정보를 지정했다.
@Configuration
public class AppConfig {
//MemberService 역할
@Bean
public MemberService memberService(){
return new MemberServiceImpl(memberRepository());
}
//MemberRepository 역할
@Bean
public MemberRepository memberRepository() {
return new MemoryMemberRepository();
}
//OrderService 역할
@Bean
public OrderService orderService(){
return new OrderServiceImpl(memberRepository(), discountPolicy());
}
// DiscountPolicy 역할
@Bean
public DiscountPolicy discountPolicy(){
// AppConfig에서 RateDiscountPolicy로만 교체하면 됨
return new RateDiscountPolicy();
}
}
//컨테이너에 빈 등록 코드
ApplicationContext ac= new AnnotationConfigApplicationContext(AppConfig.class);
<?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>
//컨테이너에 빈 등록 코드
ApplicationContext ac = new GenericXmlApplicationContext("appConfig.xml");
최근에는 스프링부트를 많이 사용하면서 XML설정은 잘 사용하지 않는다.
아직 많은 레거시 프로젝트들이 XML로 되어 있고, XML방식은 컴파일 없이 빈 설정 정보를 변경할 수 있는 장점이 있어 한번쯤 배워두는 것도 괜찮