我们可以使用xml配置bean,也可以使用JavaConfig来配置获取bean,但是无论什么方式,这种手动配置bean都很麻烦,spring可以自动扫描,将添加了@component注解的class设置为bean。我个人认为这就是自动扫描。
当然@component注解是基础,@controller 控制层、@service 业务层、@Repository dao层都是在创建注解时使用了@component。
具体的做法,就是在class上写上这几个注解,具体用哪个其实代码上都可以,但是为了区分含义,还是应该在不同的分层上用不同的注解,然后在xml 中声明启用spring自动扫描功能,就是写上这句
<context:component-scan base-package="com.yiibai.customer"/>
这里的base-package就是要扫描的包,把这里面加了注解的都解析成bean。在自动扫描的包中有一些也许是不需要的,也许只扫描一部分就可以了,剩下的不用了。那么就需要在上面的代码里在配置,
<context:component-scan base-package="com.learn.spring.springComponent" use-default-filters="true" >
<!-- <context:exclude-filter type="regex" expression="com.learn.spring.springComponent.dao"></context:exclude-filter> -->
<context:include-filter type="regex" expression="com.learn.spring.springComponent.ServiceComp"/>
<context:include-filter type="regex" expression="com.learn.spring.springComponent.Dao"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
这里include-filter就包含这些,其中regex匹配配型,annotation匹配注解。这两种都可以,但是注解要写org.springframework.stereotype.Controller这种,直接写controller当然不行,想想也是。
然后上面的
use-default-filters
默认是true,就是不管你下面的include写的是什么,这四种注解的class都会被自动扫描,我觉得就是include-filters不起作用了,但是exclude还是起作用的。false的话,那么只扫描include包含的并且去除exlude的注解,其他的丢掉。如果一个class及配置
include-filters又配置exclude-filters,那么他肯定扫描不到。
同时所有include-filters要写在exclude-filters前面,否则xml会有错误。