스프링 컨테이너 설정

귀찮Lee·2022년 6월 19일
0

Spring

목록 보기
8/30

◎ 스프링 컨테이너 인스턴스화

  • AnnotationConfigApplicationContext

    • ApplicationContext 구현

      • 아래와 같은 어노테이션이 달린 클래스로 파라미터를 전달 받음
      • @Configuration, @Component, JSR-330 메타데이터
    • @Configuration 클래스가 입력으로 제공

      • @Configuration 클래스 자체가 Bean 정의로 등록
      • 클래스 내에서 선언된 모든 @Bean 메서드도 Bean 정의로 등록
    • @Component, JSR-330

      • Bean 정의로 등록됨
      • 필요한 경우 클래스 내에서 DI 메타데이터가 사용되는 것을 가정함 (@Autowired, @Inject)
  • 스프링 컨테이너 인스턴스화 특징

    • @Configuration 방법과 @ComponentScan 방법은 보통 혼용하여 사용하지 않음
    • 주로 @ComponentScan 방법을 사용

◎ @Bean, @Configuration

@Configuration
public class AppConfig {

    @Bean
    public UserService userService() {
         return new UserServiceImpl(userRepository());
    }
    
    @Bean // Bean 의존성 정의 가능
    public OrderService orderService() {
        return new OrderServiceImpl(userRepository(), discountInfo());
    }
    
    ...
}
  • @Bean

    • 메서드-레벨 애너테이션, < bean />에서 제공하는 일부 속성을 지원
    • @Bean 정의가 되어있는 인터페이스를 구현하여 bean configuration을 설정 가능
    public interface BaseConfig {
        @Bean
        default TransferServiceImpl transferService() {
            return new TransferServiceImpl();
        }
    }
    
    @Configuration
    public class AppConfig implements BaseConfig {
        ...
    }
  • @Configuration

    • 해당 객체가 bean definitions의 소스임을 나타내는 애너테이션
    • @Bean 메서드에 대한 호출을 사용하여 bean 사이의 의존성을 정의 가능
  • @Import

    • @Configuration 클래스의 구성을 모듈화하는데 사용
    • 다른 구성 클래스에서 @Bean definitions를 가져올 수 있다.
    • 컨텍스트를 인스턴스화 할 때, import 받은 클래스만 제공하면 된다.
    • 다른 @Configuration class 에서 의존성을 가져와야 할 경우, 생성자 주입을 통해 가져올 수 있다. (스프링 프레임워크 4.3에서 지원)
    @Configuration()
    public class ConfigA {
        private final B b;
        (@Autowired)
        public ConfigA(B b){ this.b = b }
         
        @Bean
        public A a() {return new A();}
        
        @Bean
        public IncludeB includeB() {
            return new IncludeBImpl(b);
        }
    }
    
    @Configuration  // @Component를 포함하고 있음
    @Import(ConfigA.class)
    public class ConfigB {
        @Bean
        public B b() {return new B();}
    }
    
    // 컨텍스트 인스턴스화 할 때, B만 제공해도 됨
    ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);

◎ @ComponentScan

  • @ComponentScan

    • @Component가 붙은 구체화된 클래스를 스프링 빈으로 등록함
    • 의존 관계를 주입하는 @Autowired 기능도 제공 (자세한 것은 다음 velog 참고)
  • @ComponentScan vs @Configuration

    @Configuration
    @ComponentScan
    public class AutoAppConfig {
    
    }
    • @Bean으로 등록한 클래스를 정리하여 볼 수 없다.
    • @ComponentScan 사용 시, @Configuration에 있는 설정 정보도 자동 등록
      • @Configuration에 @Component도 포함되어 있음
      • 기존에 작성한 @Configuration 이 붙은 AppConfig이 있다면 정상적인 작동이 되지 않는다.
      • @Configuration 설정이 된 파일이 있을 시 아래 코드 추가
      @ComponentScan(excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = Configuration.class))
  • basePackages

    • 탐색할 패키지의 시작 위치를 지정하고, 해당 패키지부터 하위 패키지 모두 탐색
    • @ComponentScan()의 매개변수로 basePackages = “” 를 주어 탐색 시작 위치를 지정할 수 있다.
    • 지정하지 않으면, @ComponentScan이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다.
      • 설정 정보 클래스의 위치를 프로젝트 최상단에 두는 것을 추천
    • @SpringBootApplication
      • 위 어노테이션 안에 @ComponentScan이 들어있음
      • @ComponentScan 미설정시, @SpringBootApplication 기준으로 탐색
      • @SpringBootApplication이 있는 클래스를 프로젝트 최상단에 두는 것을 추천
  • 컴포넌트 스캔 대상 (@Component를 포함한 어노테이션)

    • @Component
    • @Controller & @RestController : http 통신 담당
    • @Service : 비지니스 핵심 로직 위치
    • @Repository : 스프링 데이터 접근 계층
    • @Configuration : 스프링 설정 정보 담당
  • @ComponentScan filter : 참고자료

profile
배운 것은 기록하자! / 오류 지적은 언제나 환영!

0개의 댓글