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>
相關文章
相關標籤/搜索