Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Spring's @ComponentScan search components in included JARs

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 ?

like image 666
Miciurash Avatar asked Feb 23 '15 17:02

Miciurash


People also ask

How do you scan the components in the same package of a Spring boot application to instantiate the dependent classes?

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 @component scan configuration?

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.

Which of the following is best practice of using @ComponentScan annotation in Spring?

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.

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.


2 Answers

Give it the appropriate package name to scan in the JAR.

@ComponentScan(basePackages = {"com.example.from.jar"})
like image 81
Sotirios Delimanolis Avatar answered Oct 04 '22 05:10

Sotirios Delimanolis


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 @ComponentScans.

like image 26
Ebrahim Salehi Avatar answered Oct 04 '22 06:10

Ebrahim Salehi