1

I found various was of scanning my packages for annotations, like the one here:

What those answers have in common, is that I need to pass a string, defining the base package to scan.

In my application, I do this already here:

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

and possibly in some other @ComponentScan-annotations.

One of my Components that may be found somewhere in those packages in some library is searching for other classes anotated with @MyAwsomeAnnotation to configure itself.

Now, if possible, I would like to have this component use some way to scan for annotated classes in exactly the same packages as the SpringBootApplication does.
This is what I have not found out.

Is there maybe a way to get those paths from the ApplicationContext?


An approach I was experimenting with goes as such:

  • After the bean-construction phase, (@PostConstruct) use the ApplicationContext to retrieve all Beans annotated with @ComponentScan. This will also retrieve beans that are annotateded with annotations that inherit from @ComponentScan like @SpringBootApplication.
  • Fetch the annotation and stuff the value in a Set<String> packages

The problem is, if the bean is annotated, e.g. with @SpringBootApplication, I cannot retrive the annotation @ComponentScan since it is not really present. So I would need to know all inheriting annotations, why I do only consider this an approach, not a solution.

@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()));
        }
    }
}

0 Answers0