Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - is it possible to get all packages, registered with @ComponentScan?

Is it possible to get list of all packages, registered with @ComponentScan? I need to know, what (root?) packages have been registered in my Spring Boot application...

like image 409
Arthur Avatar asked Jan 18 '15 21:01

Arthur


People also ask

How do I auto scan all packages in Spring boot?

With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.

What is the difference between @component and ComponentScan?

@Component and @ComponentScan are for different purposes. @Component indicates that a class might be a candidate for creating a bean. It's like putting a hand up. @ComponentScan is searching packages for Components.

Why do we use @ComponentScan?

@ComponentScan tells Spring in which packages you have annotated classes which should be managed by Spring. Spring needs to know which packages contain spring beans, otherwise you would have to register each bean individually in(xml file). This is the use of @ComponentScan.

How do I specify multiple packages in component scan in XML?

To add many packages to Component Scan, you should pass the String[] array to the @ComponentScan annotation.


1 Answers

Possible solution - Scanning Java annotations at runtime

Use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

API

A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates.

ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFAULT_FILTER>);

scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));

for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
    System.out.println(bd.getBeanClassName());
like image 160
Arthur Avatar answered Oct 26 '22 13:10

Arthur