@Controller control层注入
@Service service层注入,业务逻辑
@Repository dao层注入,数据业务
@Component 在业务实体不明确时使用,在其他注解中包含此注解
在application.xml文件中配置如下:
<context:component-scan basepackage=com.crp.business" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
在spring-mvc.xml中配置如下:
<context:component-scanbasepackage="com.crp.business">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
spring容器优先加载由ServletContextListener(
application.xml)产生的父容器,然后加载spring子容器(spring-mvc.xml)
include-filter:扫描当前的注解
exclude-filter: 排除扫描的注解
为什么要在子容器spring-mvc.xml中过滤@Service和@Repository呢
因为子容器Controller进行扫描装配时装配的@Service注解的实例是没有经过事务加强处理,即没有事务处理能力的Service,而父容器进行初始化的Service是保证事务的增强处理能力的。如果不在子容器中将Service exclude掉,此时得到的将是原样的无事务处理能力的Service。
关键点来了,我在spring-mvc.xml里加入了
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
然后就报错了,大致原因就是除了在
@Component中其他三个注解都包含了
@Component的注解,这样会导致扫描注解装配出现冲突,那么这种情况该怎么办,原来在context:component-scan有个use-default-filters属性,默认值是为true的,意思就是会自动扫描@Controller @Service @Repository @Component这四个注解,只要加上
<context:component-scanbasepackage="com.crp.business" use-default-filters="false">
就不会去扫描
@Component了。