@Congfigueration
@Configuration
public class AppConfig {
@Bean
public MemberService memberService() {
return new MemberServiceImple(memberRepository());
}
@Bean
public OrderService orderService() {
return new OrderServiceImple(
memberRepository(), discountPolicy());
}
@Bean
public MemberRepository memberRepository() {
return new MemoryMemberService();
}
@Bean
public DiscountPolicy discountPolicy() {
return new FixDiscountService();
}
}
@Congfigueration 어노테이션 사용 후 main에서 아래의 코드를 사용해야 동작한다.
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationAppConfigApplicationContext(AppConfig.class); //스프링 컨테이너 생성
applicationContext.getBean("memberService", MemberService.class);
...
}
ApplicationContext은 인터페이스이고 AnnotationAppConfigApplicationContext에서 Annotation을 보면 알 수 있듯이
어노테이션 기반으로 하는 설정이라는 것을 알 수 있다.
(GenericXmlApplicationContext를 사용하면 xml기반의 설정을 할 수 있는데, 장점으로는 컴파일 없이 빈 설정 정보를 변경할 수 있다.)
@Bean
new AnnotationAppConfigApplicationContext(AppConfig.class)를 실행하게 되면
AppConfig.class 스프링 컨테이너를 생성한다.
AppConfig.class 안에 @Bean 어노테이션이 붙은 메서드를 전부 호출한다.
스프링 컨테이너 안에는 스프링 빈 저장소가 있다.
ex) 빈 키 값 - memberService
ex) 빈 객체 - new MemberServiceImple(memberRepository());
로 빈을 저장한다.
빈 이름은 임의로 지정할 수 있다. 같은 이름의 빈을 지정할 경우 에러(기존 빈을 덮어버리거나)가 발생하기 때문에 항상 다른 이름으로 부여하는 게 좋다.
또 동일한 타입이 둘 이상 있을 경우 에러가 발생하는데, 빈 이름을 지정해주면 에러를 해결할 수 있다.
이때 주의할 점은 부모 타입의 빈을 가져올 때 자식 빈도 모두 가져오기 때문에 부모 빈이 두 개 이상의 자식 빈을 가져오기 때문에 에러가 발생할 수 있고, 이때도 이름을 지정해서 조회한다면 에러를 해결할 수 있다.
추가적으로
applicationContext.getBean()을 호출하면 등록된 빈을 조회할 수 있다.
BeanDefinition이 ROLE_APPLICATION은 직접 등록한 애플리케이션 빈이다.
ROLE_INFRASTRUCTURE은 스프링 내부에서 사용하는 빈이다.
'Web' 카테고리의 다른 글
| Spring Boot + GitHub Actions 으로 CI/CD 적용하기 (0) | 2025.04.05 |
|---|---|
| IoC, DI, 컨테이너 (0) | 2022.03.29 |
| 싱글톤 패턴 (0) | 2022.03.29 |
| JPA N+1 문제 (0) | 2022.03.16 |
| 관심사의 분리 (0) | 2022.03.13 |