筛选@ComponentScan特定的软件包 [英] Filter specific packages in @ComponentScan

查看:454
本文介绍了筛选@ComponentScan特定的软件包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从基础,以基于Java配置在Spring XML转换。现在,我们有这样的事情在我们的应用程序上下文:

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
    )
 )

...这将排除的两个套​​餐服务。我有我忽视的东西令人尴尬的琐碎强烈的感觉,但我无法找到一个解决方案,以过滤器的范围限制在 foo.bar

... 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.

推荐答案

您只需要创建两个配置类,两个 @ComponentScan ,你需要标注。

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

因此​​,例如,你必须为你的 foo.bar 包中的一个配置类:

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 {
}

然后是第二个配置类的<​​code> foo.baz 包:

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

然后实例化Spring上下文的时候,你会做到以下几点:

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

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

另一种方法是,你可以使用第一个配置 @ org.springframework.context.annotation.Import 注释C>类导入第二配置类。因此,例如,你可以改变 FooBarConfig 是:

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)

这篇关于筛选@ComponentScan特定的软件包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆