I made a jar with Spring components to include in multiple projects (core.jar).
I created a new Spring project, have @ComponentScan to the correct package, but it is not aware of the components in the jar.
How to make Spring's @ComponentScan search components in included JARs ?
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.
The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.
A good practice is to explicitly import a @Configuration class with the @Import annotation and add the @ComponentScan annotation to that configuration class to auto-scan only the package of that class.
@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.
Give it the appropriate package name to scan in the JAR.
@ComponentScan(basePackages = {"com.example.from.jar"})
I had a similar issue with Spring boot and @ComponentScan and this document helped me solving the issue: http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html.
The point was that my @SpringBootApplication
class was in the root package of one of basePackages of @ComponentScan
. After I moved it to a subpackage, Spring was able to recognize all @ComponentScan
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With