天天看點

spring mvc @Transaction注解不生效的解決

     spring的注解極大的友善了配置bean,将以前繁瑣的工作簡化,其中使用@Transaction注解進行事務管理更是友善,網上和各種書籍中講解@Transaction注解使用方法的文章更是數不勝數,可是大都千篇一律,而且隻是針對事務進行配置,而實際項目中,整個架構中各個功能子產品要配合協作才行。這時就會發現@Transaction注解一旦和其他注解配合使用就會失效。

網上幾乎找不到對此問題的解決方法,前幾日做一個項目中遇到了此問題,百思不得其解,後來費了很大功夫才在一片文章中找到。

此問題出現的原因就同時使用了spring的自動注解掃描和@Transaction注解。

<context:component-scan />  
           

  這句配置使得spring自動掃描@Controller、@Service、@Components、@Required、@Autowired 通常@Transaction寫在@Service的方法上,@Transactional要使用代理進行AOP處理,spring在一次性掃描時掃描到@service時,@Transactional的代理還沒生成,是以@Transactional注解會失效,解決方法就是如此配置,在spring-mvc.xml中

<context:component-scan  use-default-filters="false">  
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>     
   </context:component-scan>
           

意思是隻掃描@Controller注解

然後再application.xml中

<context:component-scan  > 
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/> 
</context:component-scan>
           

意思是隻掃描除了@Controller的所有注解

當spring解析到application.xml時,@Transactional已經生成了代理。此時在掃描@Service等注解後,@Transactional就會生效了。

在一般的書或者文章中@Transactional的使用與配置是很簡單的,但是實際應用中與其他技術進行配合就會有沖突,對照書上發現自己寫的一點不差,卻就是不生效,最好還是能夠深入架構源碼才能找到問題。

繼續閱讀