컴포넌트 스캔 상세

박찬우·2023년 12월 16일
0

스프링

목록 보기
15/88

탐색위치와 기본 스캔 대상

  • basePackages : 탐색할 패키지의 시작 위치를 지정한다. 이 패키지를 포함해서 하위 패키지를 모두 탐색
@Configuration
@ComponentScan(
        // 스프링 빈 등록시 제외할 것을 등록
        // @Configuration이 붙은 것은 제외
        excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, classes = Configuration.class),
        // hello.core.member 패키지와 하위패키지까지
        basePackages = "hello.core.member"
)
public class AutoAppConfig {

}
  • basePackageClasses : 지정한 클래스의 패키지를 탐색 시작 위치로 지정한다
@Configuration
@ComponentScan(
        // 스프링 빈 등록시 제외할 것을 등록
        // @Configuration이 붙은 것은 제외
        excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, classes = Configuration.class),
        // AutoAppConfig가 위치한 패키지와 하위 패키지까지
        basePackageClasses = AutoAppConfig.class
)
public class AutoAppConfig {

}
  • 만약 지정하지 않으면 @ComponentScan 이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다
  • 권장 방법은 패키지 위치를 지정하지 않고, 설정 정보 클래스의 위치를 프로젝트 최상단에 두는 것
  • com.hello com.hello.serivce com.hello.repository 이렇게 있을 경우
    com.hello 프로젝트 시작 루트에 AppConfig 같은 메인 설정 정보를 두고, @ComponentScan 애노테이 션을 붙이고, basePackages 지정은 생략한다.

컴포넌트 스캔 기본 대상

  • 기본적으로 useDefaultFilters옵션이 켜져 있는데 이 것을 끄면 기본 스캔 대상들이 제외된다(있다는 정도로만 알기)
  • @Component : 컴포넌트 스캔에서 사용
  • @Controller : 스프링 MVC 컨트롤러에서 사용
    • 스프링 MVC 컨트롤러로 인식
  • @Service : 스프링 비즈니스 로직에서 사용
    • 특별한 처리를 하지 않고 개발자들이 핵심 비즈니스 로직이 여기에 있다라고 비즈니스 계층을 인식하는데 도움이 됨
  • @Repository : 스프링 데이터 접근 계층에서 사용
    • 스프링 데이터 접근 계층으로 인식하고 데이터 계층의 예외를 스프링 예외로 변환해준다
  • @Configuration : 스프링 설정 정보에서 사용
    • 스프링 설정 정보로 인식하고 스프링 빈이 싱글톤을 유지하도록 추가 처리함
  • 클래스의 소스를 보면 모두 @Component 포함하고있음
@Component 
public @interface Controller { }

@Component 
public @interface Service { }

@Component 
public @interface Configuration { }

필터

  • includeFilters : 컴포넌트 스캔 대상을 추가로 지정한다
  • excludeFilters : 컴포넌트 스캔에서 제외할 대상을 지정한다
  • 컴포넌트 스캔 대상에 추가할 애노테이션
package hello.core.scan.filter;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent {

}
  • 컴포넌트 스캔 대상에서 제외할 애노테이션
package hello.core.scan.filter;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyExcludeComponent {

}
  • BeanA, BeanB
package hello.core.scan.filter;

@MyIncludeComponent
public class BeanA {
}
package hello.core.scan.filter;

@MyExcludeComponent
public class BeanB {
}

-Test

public class ComponentFilterAppConfigTest {
    @Test
    void filterScan() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(ComponentFilterAppConfig.class);
        BeanA beanA = ac.getBean("beanA", BeanA.class);
        
        // includeFilters 에 `MyIncludeComponent` 애노테이션을 추가해서 BeanA가 스프링 빈에 등록된다
        Assertions.assertThat(beanA).isNotNull();

        // excludeFilters 에 `MyExcludeComponent` 애노테이션을 추가해서 BeanB는 스프링 빈에 등록되지 않는다
        org.junit.jupiter.api.Assertions.assertThrows(
                NoSuchBeanDefinitionException.class,
                () -> ac.getBean("beanB", BeanB.class)
        );
    }

    @Configuration
    @ComponentScan(
            includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = MyIncludeComponent.class),
            excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = MyExcludeComponent.class)
    )
    static class ComponentFilterAppConfig {

    }
}
  • FilterType 종류
    • ANNOTATION : 기본값, 애노테이션을 인식해서 동작한다.
      ex) org.example.SomeAnnotation
    • ASSIGNABLE_TYPE : 지정한 타입과 자식 타입을 인식해서 동작한다.
      ex) org.example.SomeClass
    • ASPECTJ : AspectJ 패턴 사용
      ex) org.example..*Service+
    • REGEX : 정규 표현식
      ex) org\.example\.Default.*
    • CUSTOM : TypeFilter 이라는 인터페이스를 구현해서 처리
      ex) org.example.MyTypeFilter
  • 위의 기능이 있으나 구지 사용한다면 excludeFilters를 사용하기는 하지만 스프링의 기본 설정에 최대한 맞추어 사용하는 것을 권장하고, 선호하는 편임

중복 등록과 충돌

  • 자동 빈 등록 vs 자동 빈 등록
    • 컴포넌트 스캔에 의해 자동으로 스프링 빈이 등록되는데, 그 이름이 같은 경우 스프링은 오류를 발생시킨다
    • ConflictingBeanDefinitionException 예외 발생
  • 수동 빈 등록 vs 자동 빈 등록
    • 수동 빈 등록이 우선권을 가진다.
    • 수동 빈이 자동 빈을 오버라이딩 해버린다.
    • 수동 빈 등록 시 남는 로그 Overriding bean definition for bean 'memoryMemberRepository' with a different definition: replacing
@Component 
public class MemoryMemberRepository implements MemberRepository {}
@Configuration
@ComponentScan(
        excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, classes = Configuration.class)
)
public class AutoAppConfig {
    @Bean(name = "memoryMemberRepository")
    public MemberRepository memberRepository() {
        return new MemoryMemberRepository();
    }
}
  • 스프링부트에서는 위와 같은 중복 발생 시 오류를 발생 시킨다
    Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
    • spring.main.allow-bean-definition-overriding=true 옵션을 application.properties 에 등록하면 수동 등록이 우선되도록 할 수 있음
profile
진짜 개발자가 되어보자

0개의 댓글