过滤@ComponentScan中的特定软件包
问题描述:
我想在Spring中从基于XML的配置切换到基于Java的配置。现在,我们有这样的事情在我们的应用程序上下文:过滤@ComponentScan中的特定软件包
<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
。
答
您只需要为您需要的两个@ComponentScan
注释创建两个Config
类。实例你Spring上下文时
@Configuration
@ComponentScan(basePackages = {"foo.baz"})
public class FooBazConfig {
}
则:
因此,例如,你将有一个Config
类为您foo.bar
包:
@Configuration
@ComponentScan(basePackages = {"foo.bar"},
excludeFilters = @ComponentScan.Filter(value = Service.class, type = FilterType.ANNOTATION)
)
public class FooBarConfig {
}
,然后第2个Config
类为您foo.baz
包将执行以下操作:
new AnnotationConfigApplicationContext(FooBarConfig.class, FooBazConfig.class);
另一种方法是,您可以使用第一个Config
类中的@org.springframework.context.annotation.Import
注释导入第二个Config
类。因此,例如,你可以改变FooBarConfig
是:
new AnnotationConfigApplicationContext(FooBarConfig.class)
发生'Service.class'什么:
,那么只需在下手的情况下? – Deepen 2016-06-25 07:26:20