복붙노트

[SPRING] @ComponentScan의 특정 패키지 필터링

SPRING

@ComponentScan의 특정 패키지 필터링

Spring에서 XML 기반의 설정에서 Java 기반의 설정으로 전환하고 싶습니다. 이제 응용 프로그램 컨텍스트에서 이와 비슷한 것을 얻을 수 있습니다.

<context:component-scan base-package="foo.bar">
    <context:exclude-filter type="annotation" expression="o.s.s.Service"/>
</context:component-scan>
<context:component-scan base-package="foo.baz" />

하지만 내가 이렇게 쓰면 ...

 @ComponentScan(
    basePackages = {"foo.bar", "foo.baz"},
    excludeFilters = @ComponentScan.Filter(
       value= Service.class, 
       type = FilterType.ANNOTATION
    )
 )

... 두 패키지 모두에서 서비스가 제외됩니다. 당황스럽지 않은 것을 간과하고있는 강한 느낌이 들지만 필터의 범위를 foo.bar로 제한하는 해결책을 찾을 수 없습니다.

해결법

  1. ==============================

    1.필요한 두 개의 @ComponentScan 주석에 대해 두 개의 Config 클래스를 작성하기 만하면됩니다.

    필요한 두 개의 @ComponentScan 주석에 대해 두 개의 Config 클래스를 작성하기 만하면됩니다.

    예를 들어 foo.bar 패키지에 대해 하나의 Config 클래스를 가질 수 있습니다.

    @Configuration
    @ComponentScan(basePackages = {"foo.bar"}, 
        excludeFilters = @ComponentScan.Filter(value = Service.class, type = FilterType.ANNOTATION)
    )
    public class FooBarConfig {
    }
    

    그리고 나서 foo.baz 패키지를위한 두번째 Config 클래스 :

    @Configuration
    @ComponentScan(basePackages = {"foo.baz"})
    public class FooBazConfig {
    }
    

    Spring 컨텍스트를 인스턴스화 할 때 다음을 수행한다.

    new AnnotationConfigApplicationContext(FooBarConfig.class, FooBazConfig.class);
    

    다른 방법은 첫 번째 Config 클래스에서 @ org.springframework.context.annotation.Import 어노테이션을 사용하여 두 번째 Config 클래스를 가져올 수 있다는 것입니다. 예를 들어 FooBarConfig를 다음과 같이 변경할 수 있습니다.

    @Configuration
    @ComponentScan(basePackages = {"foo.bar"}, 
        excludeFilters = @ComponentScan.Filter(value = Service.class, type = FilterType.ANNOTATION)
    )
    @Import(FooBazConfig.class)
    public class FooBarConfig {
    }
    

    그러면 다음과 같이 컨텍스트를 시작하면됩니다.

    new AnnotationConfigApplicationContext(FooBarConfig.class)
    
  2. from https://stackoverflow.com/questions/16238089/filter-specific-packages-in-componentscan by cc-by-sa and MIT license