springmvc4扫描@Service导致@Transactional注解无效的解决方案

在使用spring框架过程中遇到事务注解@Transactional无效。

经过一波搜索,得到的结论是:

事务只有在spring的上下文里才能有效果。

springmvc如果加载了@Service,会导致事务无效。

解决思路很简单,就是让@Service被spring上下文扫描,而不被springmvc扫描。

解决方法:

在扫描包的时候加过滤器。

如果是使用了spring4的@ComponentScan注解来扫描包:

spring上下文↓

@ComponentScan(basePackages = {"com.xxx"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)})

springmvc上下文↓

@ComponentScan(basePackages = {"com.xxx"}, includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class})}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Service.class)})

如果是使用xml:

spring上下文↓

<!-- Activates scanning of @Repository, @Service, @Controller and @Component -->
<context:component-scan base-package="com.xxx">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

springmvc上下文↓

<!-- 自动扫描该包,功能覆盖了context:annotation-config -->
<context:component-scan base-package="com.xxx">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>

 

转载于:https://my.oschina.net/aidonggua/blog/719031

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值