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

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

通过一波搜索,获得的结论是:spring

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

springmvc若是加载了@Service,会致使事务无效。mvc

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

解决方法:spa

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

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

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)})

若是是使用xml:

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>
相关文章
相关标签/搜索