After you configure <context:component-scan base-package="com.dev2qa.examples">
in Spring bean configuration xml file, Spring container can automatically scan the java files under base-pack and it’s sub packages. If it has scanned the classes with annotations like @Component, @Service, @Repository or @Controller
, the container will register these classes as managed bean.
The <context:component-scan />
xml tag also has a use-default-filters
attribute and it’s default value is true which will let Spring container to scan all the java classes that annotated with @Component, @Repository, @Service or @Controller
etc, and register them as managed beans. If you set it’s value to false manually, then the scan will not happened.
Note: if the <context:component-scan>
is configured, the <context:annotation-config/>
tag do not need to be configured in xml, because the former contains the latter. In addition, <context:component-scan>
provides two child Tags.
<context:include-filter>
: If you find the scan granularity is a little bigger and you just want to scan @Service class under special package, then you can use this xml tags.Below example will only scan the Java classes annotated with @Service in specified base-package and register them as managed bean. Please note that you should set use-default-filters to false to make the settings take effect.<context:component-scan base-package="com.dev2qa.examples" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan>
<context:exclude-filter>
: You can use this tag when you do not want to include some special sub package or special annotation annotated classes. Below are examples.<context:component-scan base-package="com.dev2qa.examples" use-default-filters="false"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> <context:exclude-filter type="regex" expression="com\.dev2qa\.examples\.ignore\..*"/> </context:component-scan>
- Combine exclude and include filter : Generally you can combine exclude-filter and include-filter in same xml configuration. Exclude filter will run first than include filter.