I have a spring boot app, which has a library as a dependency. In this library I have several @Component
and @Configuration
classes, which are not scanned by Spring Boot app. I would like to add them to component scan, but I am not able to
How can this be achieved correctly? I think adding @ComponentScan
to MainApp
class, annotated with @SpringBootApplication
will override the default config
Thanks!
CodePudding user response:
@SpringBootApplication Annotation is the combination for @Configuration, @EnableAutoConfiguration and @ComponentScan
We can also use basePackages for scan based on requirement.
For example common package is com.example so directory will be com -> example and sub packages. So for the project there will be different packages for the different modules like controller, service, dto, repository etc...
If we want to use any package for the component scan then we can use like below script.
Hierarchy will be :
com.example.controller
com.example.service
com.example.repository
So basePackages will be look like this :
@ComponentScan(basePackages = "com.example")
Because com.example is only the path/package which is common for all other packages. So we can use like this.
CodePudding user response:
A few ways to add the library's components and configurations to the component scan in a Spring Boot application. One way is to use the @ComponentScan annotation on your main application class, which is annotated with @SpringBootApplication. You can specify the package names of the library classes to be included in the scan. For example:
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.app", "com.example.library"})
public class MainApp {
// ...
}
Another way is to use the spring.component-scan.base-package property in your application.properties or application.yml file to specify the package names of the library classes to be included in the scan. For example:
spring.component-scan.base-package=com.example.app,com.example.library
Both ways add the library classes to the component scan, without overriding the default configuration.