Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What syntax for including sub-packages in <context:component-scan>?

Tags:

java

spring

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" />
like image 242
Horace Avatar asked Jul 24 '11 14:07

Horace


People also ask

How do I give multiple base packages in component scan in Spring boot?

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.

How do I use context component scan?

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.

What is @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.

How do I scan a different package 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.


2 Answers

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?

like image 109
skaffman Avatar answered Oct 19 '22 08:10

skaffman


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.

like image 44
danny.lesnik Avatar answered Oct 19 '22 08:10

danny.lesnik