小编典典

从@ComponentScan中排除@Component

spring

我有一个要从@ComponentScan特定对象中排除的组件@Configuration

@Component("foo") class Foo {
...
}

否则,它似乎与我项目中的其他班级发生冲突。我不完全理解碰撞,但是如果注释掉@Component注释,事情就会像我希望的那样工作。但是其他依赖于此库的项目希望此类由Spring管理,因此我只想在我的项目中跳过它。

我尝试使用@ComponentScan.Filter

@Configuration 
@EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}

但它似乎不起作用。如果尝试使用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 {}

但这似乎并没有像我想要的那样从扫描中排除该组件。

如何排除呢?


阅读 1759

收藏
2020-04-13

共1个答案

小编典典

配置似乎还不错,只是你应该使用excludeFilters而不是excludes

@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}
2020-04-13