1. 程式人生 > >spring-boot 事務異常: because it is a JDK dynamic proxy that implement

spring-boot 事務異常: because it is a JDK dynamic proxy that implement

使用spring-boot做事務管理時,出現異常:The bean 'xxx' could not be injected as a 'xx.xxxx' because it is a JDK dynamic proxy that implements:

搞了半天發現是因為代理的原因;

異常資訊:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-08-01 09:37:14.845 ERROR 12264 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

The bean 'AdapterSchemeVersionService' could not be injected as a 'com.yihu.hos.rest.services.standard.adapter.AdapterSchemeVersionService' because it is a JDK dynamic proxy that implements:


Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

使用 @Transactional
開啟@Transactional 註解支援,兩種方式,一種是通過xml的方式(如下)

 <tx:annotation-driven transaction-manager="txManager"/><!-- a PlatformTransactionManager is still required -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- (this dependency is defined somewhere else) -->
        <property name="dataSource" ref="dataSource"/>
    </bean>


另外一種是使用 @EnableTransactionManagement ,將該註解標註在 @Configuration 類上,等價於上面的 <tx:annotation-driven/>
Spring推薦獎該註解標記在類(方法)而不是介面,將註解標記在介面上時,只有使用動態代理的時候才會生效,需要標記 proxy-target-class="true" 或者 mode="aspectj",如下:

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@ComponentScan("com.yihu.hos.rest")
public class BeanConfiguration {}


因為加了 @Transaction 的類會自動開啟動態代理,java的代理機制主要有 JDK動態代理 CGLIB ,報上面的錯誤是因為使用了JDK動態代理機制,我嘗試開啟@Transaction設定@EnableTransactionManagement(proxyTargetClass = true),問題解決;特此記錄一下;


參考文章:http://hrps.me/2016/11/03/spring-transaction/