Spring Boot应用中@CompentScan excludeFilters配置无效的问题

@CompentScan 注解配置需要扫描的包

excludeFilters 是其中一个配置项,用于排除不需要扫描的类

FilterType

  • ANNOTATION

根据注解来排除

  • ASSIGNABLE_TYPE

根据类类型来排除

  • ASPECTJ

根据AspectJ表达式来排除

  • REGEX

根据正则表达式来排除

  • CUSTOM

自定义FilterClass排除,需要实现org.springframework.core.type.filter.TypeFilter接口

在我们项目中,有一个core的module,里面存放了每个项目公用的package,但是有些开发人员把一些无关的初始化操作也放到了core项目中,这就导致如果A项目引用了core,那么就会做一些无用的初始化操作,由于core的子包太多,无法一个一个引用,所以使用排除法是最快的,使用REGEX进行排除操作,但是经过多次尝试,排除的类依然被spring扫描并初始化了,难道是没有效果?经过多方搜索,在一篇文章中得到启发。

https://stackoverflow.com/questions/48102883/spring-boot-componentscan-excludefilters-not-excluding/48134123

Each component scan does filtering individually. While you exclude Starter.class from SimpleTestConfig, SimpleTestConfig initializes Application, which does it's own @ComponentScan without excluding Starter. The clean way of using ComponentScan is for each ComponentScan to scan separate packages, that way each filter work fine. When 2 separate ComponentScans scan the same package (as in your tests), this does not work.

每个组件扫描都会单独进行过滤 当您从SimpleTestConfig中排除Starter.class时,SimpleTestConfig会初始化Application,它会自行执行@ComponentScan而不会排除Starter。 使用ComponentScan的简洁方法是每个ComponentScan扫描单独的包,这样每个过滤器都可以正常工作。 当2个单独的ComponentScans扫描同一个包时(如在测试中),这将不起作用。

大致的意思就是说,如果你在A类中,使用了exlucde配置,在你不需要排除的类中,有某些类B的注解上也使用了@ComponentScan,但是这个类B上注解中没有进行exclude操作,那么你在A类中的exclude将不会生效。结果扫描一下core包下面的类,确实有一个类B使用@ComponentScan,那么在A类中,同时也排除类B,A类中的exclude全部生效。

@ComponentScan(
    basePackages = {"com.scio.core"},
    excludeFilters = {
      @Filter(type = FilterType.REGEX, pattern = "com\\.scio\\.core\\.B"),
      @Filter(type = FilterType.REGEX, pattern = "com\\.scio\\.core\\.message\\..*")
    })

猜你喜欢

转载自blog.csdn.net/weixin_34345753/article/details/87108575