[英]Spring @Transactional is applied both as a dynamic Jdk proxy and an aspectj aspect
我正在通過@Transactional注釋將Spring聲明性事務添加到現有Java項目中。
當我遇到問題(與此問題無關)時,我打開了完整的調試日志記錄。 奇怪的是,我注意到以下幾點:
17:47:27,834 DEBUG HibernateTransactionManager:437 - Found thread-bound Session [org.hibernate.impl.SessionImpl@10ed8a8e] for Hibernate transaction 17:47:27,845 DEBUG HibernateTransactionManager:470 - Participating in existing transaction 17:47:27,865 DEBUG AnnotationTransactionAttributeSource:106 - Adding transactional method 'updateUserProfile' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '' 17:47:27,875 DEBUG AnnotationTransactionAspect:321 - Skipping transactional joinpoint [se.myservice.UserService.updateUserProfile] because no transaction manager has been configured
經過一些調試后,我發現前三個日志條目,它說它找到一個線程綁定會話並使用該事務,由我的UserService類上的JdkDynamicAopProxy生成。
最后一條日志消息看起來很驚人。 它在方法執行之前在連接點調用。 查看AnnotationTransactionAspect的源時,如果未設置事務管理器,則會生成此消息。 在這種情況下,因為Spring從不在這方面執行任何依賴注入。
在我看來,兩種不同的“風格”交易都適用:動態代理和方面。 我唯一與事務相關的配置是:
<tx:annotation-driven transaction-manager="txManager" />
我們在項目中使用了AspectJ,但是在我的aop.xml中沒有注冊AnnotationTransactionAspect方面。 我們正在使用Spring 3.0.2.RELEASE。
我應該對此感到震驚嗎? Spring會為我注冊這方面嗎? 使用AspectJ時我不應該使用annotation-driven
嗎?
很奇怪,聽起來你有這樣的配置:
<tx:annotation-driven
transaction-manager="transactionManager" mode="aspectj" />
(使用AspectJ的事務支持,而不是JDK代理)
由於您的配置沒有mode屬性,因此默認情況應該啟動(代理模式)。 但是AnnotationTransactionAspect是aspectj模式使用的確切方面。
使用java配置獲取aspectj事務。
@EnableWebMvc
@Configuration
@ComponentScan("com.yourdomain")
@EnableTransactionManagement(mode=AdviceMode.ASPECTJ)
public class ApplicationConfig extends WebMvcConfigurerAdapter {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
//...
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager bean = new JpaTransactionManager(entityManagerFactory().getObject());
return bean ;
}
@Bean
public AnnotationTransactionAspect annotationTransactionAspect() {
AnnotationTransactionAspect bean = AnnotationTransactionAspect.aspectOf();
bean.setTransactionManager(transactionManager());
return bean;
}
}
如果你使用maven:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
<showWeaveInfo>true</showWeaveInfo>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
如果您正在使用eclipse,這將確保在eclipse中部署時完成編織:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.