spring mvc注解@Controller @Service @Repository @Component详解配置以及相关问题分析


@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了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值