Usage of <context:component-sacn>

 

  After configuring this tag in xml, spring can automatically scan the java files under base-pack or under sub-packages. If it scans classes with annotations such as @Component @Controller@Service, it will register these classes as beans

Note: If <context:component-scan> is configured, then the <context:annotation-config/> tag can not be configured in xml, because the former includes the latter. In addition, <context:component-scan> also provides two subtags

1.        <context:include-filter>

2.       <context:exclude-filter>

Before explaining these two subtags, let's talk about <context:component-scan> has a use-default-filters attribute, and changing the attribute defaults to true, which means that all files marked with @Component under the specified package will be scanned . class, and registered as a bean. That is , the sub-annotation @Service, @Reposity, etc. of @Component . So if you just write this in the configuration file

<context:component-scan base-package="tv.huan.weisp.web"/>

 Use-default-filter is true at this time, then it will scan all java classes under the base-package package or sub-packages, and register the matching java classes as beans.

 

 It can be found that the granularity of this scan is a bit too large. What if you only want to scan the Controller under the specified package? At this point, the subtag <context:incluce-filter> comes into play. As follows

<context:component-scan base-package="tv.huan.weisp.web .controller">  

<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   

</context:component-scan>  

In this way, only the java classes under @Controller specified by base-package will be scanned and registered as beans

But because use-dafault-filter is not specified above, the default is true, so when the above configuration is changed to the following, it will produce results contrary to your expectations (note that the base-package package is worth changing)

<context:component-scan base-package="tv.huan.weisp.web">  

<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   

</context:component-scan>  

At this point, spring not only scans @Controller, but also scans the java class annotated @Service under the subpackage service package where the specified package is located

At this time, the specified include-filter does not work, as long as use-default-filter is set to false. In this way, you can avoid configuring multiple package names in base-packeage, which is not a very elegant way to solve this problem.

另外在我参与的项目中可以发现在base-package指定的包中有的子包是不含有注解了,所以不用扫描,此时可以指定<context:exclude-filter>来进行过滤,说明此包不需要被扫描。综合以上说明

Use-dafault-filters=”false”的情况下:<context:exclude-filter>指定的不扫描,<context:include-filter>指定的扫描

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326092281&siteId=291194637