Filter specific packages in @ComponentScan

后端 未结 1 1496
北海茫月
北海茫月 2020-11-28 09:58

I want to switch from XML based to Java based configuration in Spring. Now we have something like this in our application context:



        
相关标签:
1条回答
  • 2020-11-28 10:21

    You simply need to create two Config classes, for the two @ComponentScan annotations that you require.

    So for example you would have one Config class for your foo.bar package:

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

    and then a 2nd Config class for your foo.baz package:

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

    then when instantiating the Spring context you would do the following:

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

    An alternative is that you can use the @org.springframework.context.annotation.Import annotation on the first Config class to import the 2nd Config class. So for example you could change FooBarConfig to be:

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

    Then you would simply start your context with:

    new AnnotationConfigApplicationContext(FooBarConfig.class)
    
    0 讨论(0)
提交回复
热议问题