I am using Spring and I have a long list of subpackages, do I have to specify them one by one in the <context:component-scan>
tag?
<context:component-scan base-package="com.fooapp.mainpackage,
com.fooapp.mainpackage.subpackage1,
com.fooapp.mainpackage.subpackage2,
com.fooapp.mainpackage.subpackage3" />
Scanning Multiple Packages in Spring Boot Next, Create another class in the different packages as below. To add many packages to Component Scan, you should pass the String[] array to the @ComponentScan annotation.
Put this “ context:component ” in bean configuration file, it means, enable auto scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan this folder and find out the bean (annotated with @Component) and register it in Spring container.
@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.
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.
Component-scanning supports package hierarchies, so this should work:
<context:component-scan base-package="com.fooapp.mainpackage"/>
This is easy and quicker to verify for yourself - did you try it?
In addition I would to add that by default, classes annotated with @Component
, @Repository
, @Service
, @Controller
, or a custom annotation that itself is annotated with @Component are the only detected candidate components.
You can change this behavior by applying custom filters which are include-filter
or exclude-filter
For example:
<context:component-scan base-package="com.vanilla">
<context:exclude-filter
type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
It will exclude all @Repository annotations.
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