我有一个组件,我想从@ComponentScan特定的一个组件中排除@Configuration:
@Component("foo") class Foo {
...
}
Run Code Online (Sandbox Code Playgroud)
否则,它似乎与我项目中的其他类冲突.我不完全理解碰撞,但是如果我注释掉@Component注释,事情就像我想要的那样.但是依赖这个库的其他项目希望这个类由Spring管理,所以我想在我的项目中跳过它.
我试过用@ComponentScan.Filter:
@Configuration
@EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}
Run Code Online (Sandbox Code Playgroud)
但它似乎不起作用.如果我尝试使用FilterType.ASSIGNABLE_TYPE,我得到一个奇怪的错误,无法加载一些看似随机的类:
引起:java.io.FileNotFoundException:类路径资源[junit/framework/TestCase.class]无法打开,因为它不存在
我也尝试使用type=FilterType.CUSTOM如下:
class ExcludeFooFilter implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
return metadataReader.getClass() == Foo.class;
}
}
@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}
Run Code Online (Sandbox Code Playgroud)
但这似乎并没有像我想要的那样从扫描中排除组件.
我如何排除它?
我有一个类,我想在组件扫描时排除.我使用下面的代码来做到这一点,但似乎没有工作,虽然一切似乎都是正确的
@ComponentScan(basePackages = { "common", "adapter", "admin"}, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ServiceImpl.class) })
Run Code Online (Sandbox Code Playgroud)
实际上我想要有"ServiceImpl"类,它实现了"服务"接口,正在我的其余api逻辑中使用,在进行api的集成测试时,我想要排除这个实现并加载模拟的实现.但这似乎并没有发生,因为即使使用上面我得到以下错误
No qualifying bean of type [admin.Service] is defined: expected single matching bean but found 2: ServiceMockImpl,ServiceImpl
Run Code Online (Sandbox Code Playgroud)
我花了太多时间在这上面但没有任何作用.
任何帮助表示赞赏.
最近,Spring Boot 添加了TypeExcludeFilters。一个突出的用例是SpringBootApplication注释。
Spring Boot 1.4 之前:
// ...
@ComponentScan
public @interface SpringBootApplication {
// ...
Run Code Online (Sandbox Code Playgroud)
从 Spring Boot 1.4 开始:
// ...
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM,
classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {
// ...
Run Code Online (Sandbox Code Playgroud)
主要动机似乎是改进 Spring 中的测试支持,但我无法直观地理解它的作用以及它在什么情况下可以带来好处。
有人可以用一个简单的例子说明如何使用这个新概念吗?
背景:更改发生在 Spring 1.4.0 中,提交为 513dec718fd3e7449ec76b6a916f4696d1942d5d:
添加一个新的 TypeFilter 专门用于排除候选组件。该过滤器应用于
@SpringBootApplication并允许测试动态贡献排除过滤器,以便可以排除特定类别的组件。
我想重用 Spring 生产上下文配置,但用另一个 bean 替换一些 bean。如果我想用模拟覆盖它们,我会使用@MockBean,它完全满足我的需要(覆盖 bean),但不允许我自己配置一个新的 bean。
我知道还有另一种使用方法,@ContextConfiguration但对我来说似乎太冗长了。
谢谢。