Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

spring - Filter specific packages in @ComponentScan

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

<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" />

But if I write something like this...

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

... it will exclude services from both packages. I have the strong feeling I'm overlooking something embarrassingly trivial, but I couldn't find a solution to limit the scope of the filter to foo.bar.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...