在使用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>