블로그 이미지

ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • @Configuration이 붙지 않은 클래스의 메서드에 @Bean을 붙이면 어떻게 될까?
    Programming/Spring 2022. 5. 18. 14:40

    Spring에서 Container에 Bean을 등록하는 방법중 하나로 다음과 같이 Java Config 을 이용하는 방법이 있다.

    @Configuration
    public class AuthenticationPrincipalConfig {
    
        @Bean
        public AuthService authService() {
            return new AuthService();
        }
    }

    @Configure 은 해당 클래스가 빈 정의를 위한 목적이라는 것을 표시해주는 목적으로 사용된다. 그런데, 다음과 같이 @Configuration 없이 @Bean 만 존재한다면 어떻게 될까?

    public class AuthenticationPrincipalConfig {
    
        @Bean
        public AuthService authService() {
            return new AuthService();
        }
    }

    결론만 말하자면, @Configuration 이 없다면 "lite" 모드로 처리된다.

     

    그럼 lite 모드가 뭘까?

    @Configuration 이 붙은 클래스와 다르게 lite모드에서는 @Bean 메서드가 bean간의 의존성을 선언할 수 없다. 예를 들어보자

    @Configuration
    public class AuthenticationPrincipalConfig {
    
        @Bean
        public SharedDependency sharedDependency() {
        	return new SharedDependency();
        }
        
        @Bean
        public AuthService authService() {
            return new AuthService(sharedDependency());
        }
        
        @Bean
        public AuthService2 authService2() {
            return new AuthService2(sharedDependency());
        }
        
    
    }

    위의 코드에서 sharedDependency() 를 authService 와 authService2 에서 호출하고 있다.(sharedDependency 가 다른 설정 클래스에 있어도 동작은 같다.)

    @Configuration 이 붙은 full mode 설정 클래스에서는 CGLIB 을 이용해 프록시 객체를 생성한다. 메서드를 호출했을 때 빈이 이미 생성되어 있다면 새로운 빈을 생성하지 않고 캐싱된 빈을 불러온다. 따라서, 스프링 빈 스코프가 싱글톤으로 설정되어 있다면 sharedDependency는 여러번 호출되지만, 스프링이 단 하나의 인스턴스만 생성하도록 보장한다.

    public class AuthenticationPrincipalConfig {
    
        @Bean
        public SharedDependency sharedDependency() {
        	return new SharedDependency();
        }
        
        @Bean
        public AuthService authService() {
            return new AuthService(sharedDependency());
        }
        
        @Bean
        public AuthService2 authService2() {
            return new AuthService2(sharedDependency());
        }
        
    
    }

    하지만 위와 같이 클래스에 @Configuration이 없는 순수한 클래스이거나, @Component 가 붙은 클래스라면 sharedDependency를 호출할 때 마다 인스턴스를 새로 생성한다. lite 모드에서는 프록시 객체를 생성하지 않고 바로 객체를 생성해버리기 때문이다. 즉, 빈 스코프가 싱글톤으로 설정되어 있으나 스프링이 싱글톤을 보장해주지 못한다는 것이다.

     

     

     

    'Programming > Spring' 카테고리의 다른 글

    AOP 용어 정리  (0) 2022.09.19
    @Transactional의 롤백  (1) 2022.05.18
    DI(Dependency Injection)의 종류와 장단점  (2) 2022.04.26

    댓글

Designed by Tistory.