spring 在@ComponentScan 中过滤特定的包
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16238089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter specific packages in @ComponentScan
提问by Landei
I want to switch from XML based to Java based configuration in Spring. Now we have something like this in our application context:
我想在 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" />
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 bothpackages. 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.
...它将从两个包中排除服务。我有一种强烈的感觉,我忽略了一些令人尴尬的琐碎事情,但我找不到将过滤器的范围限制为foo.bar.
回答by DB5
You simply need to create two Configclasses, for the two @ComponentScanannotations that you require.
您只需要为您需要Config的两个@ComponentScan注释创建两个类。
So for example you would have one Configclass for your foo.barpackage:
因此,例如Config,您的foo.bar包将有一个类:
@Configuration
@ComponentScan(basePackages = {"foo.bar"},
excludeFilters = @ComponentScan.Filter(value = Service.class, type = FilterType.ANNOTATION)
)
public class FooBarConfig {
}
and then a 2nd Configclass for your foo.bazpackage:
然后是Config您的foo.baz包裹的第二类:
@Configuration
@ComponentScan(basePackages = {"foo.baz"})
public class FooBazConfig {
}
then when instantiating the Spring context you would do the following:
然后在实例化 Spring 上下文时,您将执行以下操作:
new AnnotationConfigApplicationContext(FooBarConfig.class, FooBazConfig.class);
An alternative is that you can use the @org.springframework.context.annotation.Importannotation on the first Configclass to import the 2nd Configclass. So for example you could change FooBarConfigto be:
另一种方法是您可以使用@org.springframework.context.annotation.Import第一个Config类上的注释来导入第二个Config类。例如,您可以更改FooBarConfig为:
@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)

