本文介绍了在@ComponentScan 中过滤特定的包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Spring 中从基于 XML 的配置切换到基于 Java 的配置.现在我们的应用程序上下文中有这样的东西:

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 注释创建两个 Config 类.

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

例如,您的 foo.bar 包将有一个 Config 类:

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

然后是 foo.baz 包的第二个 Config 类:

and then a 2nd Config class for your foo.baz package:

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

另一种方法是您可以在第一个 Config 类上使用 @org.springframework.context.annotation.Import 批注来导入第二个 Config 类.例如,您可以将 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 中过滤特定的包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 06:03