關於Spring事務代理類型轉換問題($ProxyXX cannot be cast to 類型)(二)

     緊接 上文 ....
2、解決方案
      後來在網上搜了一下,這樣的問題不少,可是正真的解決方案並很少。參考http://mopishv0.blog.163.com/blog/static/54455932200911118572079寫道
      spring的文檔中這麼寫的:Spring AOP部分使用JDK動態代理或者CGLIB來爲目標對象建立代理,若是被代理的目標對象實現了至少一個接口,則會使用JDK動態代理。全部該目標類型實現的接口都將被代理。若該目標對象沒有實現任何接口,則建立一個CGLIB代理。使用beanNameAutoProxyCreator來進行事務代理的話,他的proxyTargetClass這個屬性設置爲false(默認是false),即便用JDK動態代理,若是你的service類沒有實現接口的話,就會報類型轉換錯誤。
    解決辦法有
    1
、給service類添加一個接口iService,讓service類實現它,則建立代理類時使用JDK動態代理就不會出現問題
    2、設置beanNameAutoProxyCreatorproxyTargetClass屬性爲true,意思是強制使用CGLIB代理,前提是你已經將CGLIB包加入到項目中
    推敲了很長時間,由於以前Spring事務用到的並很少,因此不是很瞭解。
    第一種方法修改UserDao類也實現IDAO接口,可是沒有解決。照樣報錯....
    因而使用了第二種方案,修改了Spring事物配置信息,在原有的配置下加了一句配置以下:
<!-- 配置事務操做 -->
< bean id ="transactionManager" class ="org.springframework.orm.hibernate3.HibernateTransactionManager">
    < property name ="sessionFactory" ref ="sessionFactory" />
</ bean >
< tx:advice id ="txAdvice" transactionmanager ="transactionManager">
    < tx:attributes >
        < tx:method name ="add*" propagation ="REQUIRED" />
        < tx:method name ="insert*" propagation ="REQUIRED" />
        < tx:method name ="delete*" propagation ="REQUIRED" />
        < tx:method name ="update*" propagation ="REQUIRED" />
        < tx:method name ="find*" read-only ="false" propagation ="SUPPORTS" />
        < tx:method name ="select*" read-only ="false" propagation ="SUPPORTS" />
    </ tx:attributes >
</ tx:advice >
< aop:config >
    < aop:pointcut id ="point" expression ="execution(* com.dao.*.*(..))" />
    < aop:advisor advice-ref ="txAdvice" pointcut-ref ="point" />
</ aop:config >
<!--   注意下面的配置 -->
< aop:aspectj-autoproxy proxy-target-class ="true"/>
     注意:最後一行配置信息。
     這樣以後就解決了,並且測試結果以下:
INFO [STDOUT] com.dao.UserDao@13ba812
INFO [STDOUT]
true
INFO [STDOUT]
true
INFO [STDOUT]
true
   又學了一招,很好很強大。。。接着要好好研究一下JDK動態代理和CGLIB代理(cglib.jarasm.jar)
相關文章
相關標籤/搜索