1. 程式人生 > >spring mvc @Transaction註解不生效的解決

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的使用與配置是很簡單的,但是實際應用中與其他技術進行配合就會有衝突,對照書上發現自己寫的一點不差,卻就是不生效,最好還是能夠深入框架原始碼才能找到問題。