Lan*_*dei 35 spring annotations
我想在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" />
Run Code Online (Sandbox Code Playgroud)
但如果我写这样的东西......
@ComponentScan(
basePackages = {"foo.bar", "foo.baz"},
excludeFilters = @ComponentScan.Filter(
value= Service.class,
type = FilterType.ANNOTATION
)
)
Run Code Online (Sandbox Code Playgroud)
...它将从两个包中排除服务.我有强烈的感觉,我忽略了一些令人尴尬的琐碎,但我找不到一个解决方案来限制过滤器的范围foo.bar.
DB5*_*DB5 40
您只需要为您需要Config的两个@ComponentScan注释创建两个类.
例如Config,您的foo.bar包将有一个类:
@Configuration
@ComponentScan(basePackages = {"foo.bar"},
excludeFilters = @ComponentScan.Filter(value = Service.class, type = FilterType.ANNOTATION)
)
public class FooBarConfig {
}
Run Code Online (Sandbox Code Playgroud)
然后是Config你的foo.baz包裹的第二堂课:
@Configuration
@ComponentScan(basePackages = {"foo.baz"})
public class FooBazConfig {
}
Run Code Online (Sandbox Code Playgroud)
然后在实例化Spring上下文时,您将执行以下操作:
new AnnotationConfigApplicationContext(FooBarConfig.class, FooBazConfig.class);
Run Code Online (Sandbox Code Playgroud)
另一种方法是您可以@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 {
}
Run Code Online (Sandbox Code Playgroud)
然后,您只需使用以下命令启动上下文:
new AnnotationConfigApplicationContext(FooBarConfig.class)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49102 次 |
| 最近记录: |