1

我发现各种各样的方法是扫描我的包中的注释,就像这里的一个:

这些答案的共同点是我需要传递一个字符串,定义要扫描的基本包。

在我的应用程序中,我已经在这里执行此操作:

@SpringBootApplication(scanBasePackages = "org.myorg.pro")

并且可能在其他一些@ComponentScan注释中。

我的组件之一可能在某个库的这些包中的某处找到,它正在搜索带有注释的其他类@MyAwsomeAnnotation以配置自身。

现在,如果可能的话,我想让这个组件使用某种方式来扫描与它完全相同的包中的注释类SpringBootApplication
这是我没有发现的。

有没有办法从 ApplicationContext 中获取这些路径?


我正在尝试的一种方法是这样的:

  • 在 bean 构建阶段之后,( @PostConstruct) 使用 ApplicationContext 检索所有用 注释的 Bean @ComponentScan。这还将检索使用从like继承的注释进行注释的 bean 。@ComponentScan@SpringBootApplication
  • 获取注释并将值填充到Set<String> packages

问题是,如果对 bean 进行了注释,例如使用 @SpringBootApplication,我无法检索注释 @ComponentScan,因为它实际上并不存在。所以我需要知道所有继承注释,为什么我只认为这是一种方法,而不是解决方案。

@PostConstruct
private void initialize() {
    Collection<Object> scanners = context.getBeansWithAnnotation(ComponentScan.class).values();
    for (Object scanner : scanners) {
        Class clazz = scanner.getClass();
        Annotation[] annotations = clazz.getAnnotations();
        if(clazz.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan annotation = (ComponentScan) clazz.getAnnotation(ComponentScan.class);
            packages.addAll(Arrays.asList(annotation.basePackages()));
        }
        if(clazz.isAnnotationPresent(SpringBootApplication.class)) {
            SpringBootApplication annotation = (SpringBootApplication) clazz.getAnnotation(SpringBootApplication.class);
            packages.addAll(Arrays.asList(annotation.scanBasePackages()));
        }
    }
}
4

0 回答 0