小编典典

筛选@ComponentScan中的特定软件包

spring

我想在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


阅读 786

收藏
2020-04-13

共1个答案

小编典典

你只需要为Config所需的两个@ComponentScan注释创建两个类。

因此,例如Config,你的foo.bar包装将有一个类:

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

然后是Config你的foo.baz包裹的二等舱:

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

然后在实例化Spring上下文时,你将执行以下操作:

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

另一种选择是,你可以@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 {
}

然后,你只需从以下内容开始上下文:

new AnnotationConfigApplicationContext(FooBarConfig.class)
2020-04-13