ApplicaitonContext
AnnotationConfigApplicationContext ac =
new AnnotationConfigApplicationContext(AppConfig.class);
- 스프링 컨테이너라고 부름
- 인터페이스
스프링 컨테이너 생성 과정
- 스프링 컨테이너를 생성할 때는 구성 정보를 지정해주어야 함
- 여기서는 AppConfig.class를 구성 정보로 지정
- 빈 이름은 메서드 이름을 사용
- 빈 이름은 직접 부여 가능
- @Bean(name = "빈 이름 지정")
- 빈 이름은 항상 다른 이름을 부여
스프링으로 전환하기
package hello.core;
import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import hello.core.member.MemberService;
import hello.core.member.MemberServiceImpl;
import hello.core.member.MemoryMemberRepository;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MemberService memberService(){
return new MemberServiceImpl(memberRepository());
}
@Bean
public MemoryMemberRepository memberRepository() {
return new MemoryMemberRepository();
}
@Bean
public OrderService orderService(){
return new OrderServiceImpl(memberRepository(), discountPolicy());
}
@Bean
public DiscountPolicy discountPolicy(){
// return new FixDiscountPolicy();
return new RateDiscountPolicy();
}
}
- @Configuration 추가
- @Bean 추가
package hello.core;
import hello.core.member.Grade;
import hello.core.member.Member;
import hello.core.member.MemberService;
import hello.core.member.MemberServiceImpl;
import hello.core.order.Order;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class OrderApp {
public static void main(String[] args) {
// AppConfig appConfig = new AppConfig();
// MemberService memberService = appConfig.memberService();
// OrderService orderService = appConfig.orderService();
// MemberService memberService = new MemberServiceImpl();
// OrderServiceImpl orderService = new OrderServiceImpl();
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
MemberService memberService = applicationContext.getBean("memberService", MemberService.class);
OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
Long memberId = 1L;
Member member = new Member(memberId, "memberA", Grade.VIP);
memberService.join(member);
Order order = orderService.createOrder(memberId, "itemA", 20000);
System.out.println("order = " + order);
}
}
- 스프링 컨테이너 생성
'Spring > Basic' 카테고리의 다른 글
@ComponentScan (0) | 2024.08.21 |
---|---|
@Configuration (0) | 2024.08.20 |
Singleton (0) | 2024.08.20 |
AppConfig (0) | 2024.08.15 |
좋은 객체 지향 설계의 5가지 원칙(SOLID) (0) | 2024.08.13 |