在使用spring框架过程当中遇到事务注解@Transactional无效。java
通过一波搜索,获得的结论是:spring
事务只有在spring的上下文里才能有效果。express
springmvc若是加载了@Service,会致使事务无效。mvc
解决思路很简单,就是让@Service被spring上下文扫描,而不被springmvc扫描。框架
解决方法:spa
在扫描包的时候加过滤器。.net
spring上下文↓code
@ComponentScan(basePackages = {"com.xxx"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)})
springmvc上下文↓component
@ComponentScan(basePackages = {"com.xxx"}, includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class})}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Service.class)})
spring上下文↓xml
<!-- 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>