스프링 컨테이너는 싱글톤 레지스트리다. 따라서 스프링 빈이 싱글톤이 되도록 보장해줘야 한다.
그런데 스프링이 자바 코드까지 어떻게 하기는 어렵다.
AppConfig의 코드를 보면 memberService는 분명 3번 호출되어야 하는 것이 맞다...
어떻게 스프링은 싱글톤을 보장해줄 수 있을까?
이 모든 비밀은 @Configuration에 있다.
먼저, AppConfig.class 타입의 빈을 조회해보자
@Test
void configurationDeep(){
ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
// AppConfig도 빈으로 등록된다.
AppConfig bean = ac.getBean(AppConfig.class);
System.out.println("bean = " + bean.getClass());
}
//실행결과
bean = class hello.core.AppConfig$$SpringCGLIB$$0
- @Configuration 으로 등록한 AppConfig 클래스도 빈으로 등록된다.
- 그렇다면 bean.getClass( ) 의 결과는 class hello.core.AppConfig 일 것이다.
- 하지만 예상과는 다르게 클래스명에 xxxCGLIB가 붙으면서 상당히 복잡해진 것을 볼 수 있다.
그 이유는 바로, 우리가 만든 AppConfig 클래스가 아니라 스프링이 CGLIB라는 바이트코드 조작 라이브러리를 사용해서
AppConfig 클래스를 상속받은 임의의 다른 클래스를 만들고, 그 다른 클래스를 스프링 빈으로 등록한 것이다
스프링이 빈을 등록하는 과정에서 조작을 해 다른 것을 빈으로 넣어버렸다 !!
그렇다면 스프링은 왜 이런 짓을 했을까?
참고: AppConfig@CGLIB는 AppConfig의 자식 타입이므로, AppConfig 타입으로 조회 할 수 있다
스프링이 우리가 등록하고자 한 AppConfig 대신 AppConfig를 상속받은 임의의 클래스를 빈으로 등록시킨 이유는
싱글톤을 보장해주기 위해서다.
기존의 우리가 작성한 순수 자바코드로 구성된 AppConfig 자체로 스프링 컨테이너를 구성한다면
memberService가 여러번 호출되어 서로 다른 객체가 여러개 생성될 것이고 이는 싱글톤이 깨지게 된다.
그래서 스프링은 우리가 만든 클래스를 상속받고 조작을 통해 빈이 싱글톤으로 관리될 수 있도록 하는 것이다.
아마도 다음과 같이 바이트 코드를 조작해서 작성되어 있을 것이다.(실제로는 CGLIB의 내부 기술을 사용하는데 매우 복잡하다.)
AppConfig@CGLIB 예상 코드
@Bean
public MemberRepository memberRepository() {
if (memoryMemberRepository가 이미 스프링 컨테이너에 등록되어 있으면?) {
return 스프링 컨테이너에서 찾아서 반환;
}
else { //스프링 컨테이너에 없으면
기존 로직을 호출해서 MemoryMemberRepository를 생성하고 스프링 컨테이너에 등록
return 반환
}
- @Bean이 붙은 메서드마다 이미 스프링 빈이 존재하면 존재하는 빈을 반환하고
- 스프링 빈이 없으면 생성해서 스프링 빈으로 등록하고 반환하는 코드가 동적으로 만들어진다.
- 이렇게 해서 싱글톤을 보장한다.
그래서 앞의 글 에서 memberRepository를 여러번 호출했더라도
첫 호출로 빈을 등록한 이후에는 스프링 컨테이너에서 찾아서 만들어진 빈을 반환해줬기 때문에 여러번 메서드를 호출했더라도
모두 같은 객체가 조회됐던 것이다.
✅ 위의 내용들을 간단하게 정리해본다면, 스프링은 우리가 @Configuration을 써서 스프링의 설계도로 지정한 클래스를 그대로 사용하는 것이 아닌 , 싱글톤을 보장해주기 위해 우리가 만든 클래스를 상속받은 임의의 클래스를 사용한다.
그렇다면, @Configuration 을 적용하지 않고, @Bean 만 적용하면 어떻게 될까?
- @Configuration을 통해 스프링은 해당 클래스가 설정클래스라는 것을 아는데, 이것이 없다면 @Bean이 있더라도 빈 등록이 안될까?
- @Configuration 이 없다면, 우리가 작성한 순수 클래스가 스프링의 설정 클래스로 이용될까?
이를 확인하기 위해 AppConfig 클래스의 @Configuration 어노테이션을 주석처리하고 테스트 코드를 다시 실행시켜보자
// 테스트 실행결과
call AppConfig.memberService
call AppConfig.memberRepository
18:37:52.832 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory --
Creating shared instance of singleton bean 'memberRepository'
call AppConfig.memberRepository
18:37:52.832 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory --
Creating shared instance of singleton bean 'orderService'
call AppConfig.orderService
call AppConfig.memberRepository
18:37:52.835 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory --
Creating shared instance of singleton bean 'discountPolicy'
bean = class hello.core.AppConfig
bean = class hello.core.AppConfig
출력결과 우리가 만든 순수한 AppConfig 클래스가 출력되었다.
@Configuration 이 없다면 우리가 작성한 순수 Appconfig클래스가 스프링 컨테이너의 설정클래스가 된다.
또한 @Configuration 이 없더라도 AppConfig의 @Bean이 모두 빈으로 등록된다.
// 설정된 빈 이름 모두 출력하기
for (String beanDefinitionName : ac.getBeanDefinitionNames()) {
System.out.println("beanDefinitionName = " + beanDefinitionName);
}
//실행결과
beanDefinitionName = appConfig
beanDefinitionName = memberService
beanDefinitionName = memberRepository
beanDefinitionName = orderService
beanDefinitionName = discountPolicy
그렇다면 싱글톤 문제는 어떨까? memberRepository 메서드가 여러번 호출 될텐데 이전과 무슨 차이가 있을까?
call AppConfig.memberService
call AppConfig.memberRepository
call AppConfig.memberRepository
call AppConfig.orderService
call AppConfig.memberRepository
실행결과, @Configuration 어노테이션이 있을때 와는 다르게 call AppConfig.memberRepository 가 세 번 호출 되었다.
1번은 스프링 컨테이너에 @Bean을 등록하기 위해서, 2번은 각각 memberRepository( ) 를 호출했기 때문이다.
즉, 싱글톤이 깨진다.
- @Configuration 이 없는 경우 memberService를 호출할 때마다 새로운 객체가 생성되는지 테스트 코드의 실행결과를 통해 알아보자
@Test
@DisplayName("@Configuraion과 싱글톤")
void ConfiguraionSingletonTest(){
ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
MemberServiceImpl memberService = ac.getBean("memberService", MemberServiceImpl.class);
OrderServiceImpl orderService = ac.getBean("orderService", OrderServiceImpl.class);
MemberRepository memberRepository = ac.getBean("memberRepository", MemberRepository.class);
System.out.println("memberService -> memberRepository" + memberService.getMemberRepository());
System.out.println("orderService -> memberRepository" + orderService.getMemberRepository());
System.out.println("memberRepository = " + memberRepository);
Assertions.assertThat(memberService.getMemberRepository()).isSameAs(memberRepository);
Assertions.assertThat(orderService.getMemberRepository()).isSameAs(memberRepository);
}
//실행결과
memberService -> memberRepositoryhello.core.member.MemoryMemberRepository@52066604
orderService -> memberRepositoryhello.core.member.MemoryMemberRepository@340b9973
memberRepository = hello.core.member.MemoryMemberRepository@56113384
테스트 코드 실행결과, 각각의 memberRepository는 모두 다른 객체임을 알 수 있다.
또 다른 문제점은 memberService와 orderService의 memberRepository는 스프링이 관리하는 빈이 아니라는 것이다.
@Bean
public MemoryMemberRepository memberRepository() {
System.out.println("call AppConfig.memberRepository");
return new MemoryMemberRepository();
}
@Bean으로 등록된 memberRepository는 스프링 빈으로 등록되지만
memberService와 orderService가 호출하는 memberRepository( )는 new MemoryMemberRepository로 새로운 객체를 생성해주는 것이므로 스프링 빈이 아니다.
정리
- @Bean만 사용해도 스프링 빈으로 등록되지만, 싱글톤을 보장하지 않는다.
- memberRepository()처럼 의존관계 주입이 필요해서 메서드를 직접 호출할 때 싱글톤을 보장하지 않는다
- 크게 고민할 것이 없다. 스프링 설정 정보는 항상 @Configuration 을 사용하자
'Spring > 김영한 스프링 핵심원리 - 기본편' 카테고리의 다른 글
[섹션6-2] 탐색할 위치와 기본 스캔 대상 (0) | 2024.02.25 |
---|---|
[섹션6-1] 컴포넌트 스캔과 의존관계 자동주입 (0) | 2024.02.20 |
[섹션5-5] @Configuration과 싱글톤 (0) | 2024.02.18 |
[섹션5-4] 싱글톤 방식의 주의점 (0) | 2024.02.17 |
[섹션5-3] 싱글톤 컨테이너 (0) | 2024.02.15 |