问题描述
我使用 @Configuration
注释来配置spring而不是xml文件。我正在配置具有不同会话工厂和不同事务管理器的2个数据源。我在这里遇到了一个问题 @EnableTransactionManagement
注释。我在其文档中读到,
I am using @Configuration
annotation for configuration of spring instead of xml file. I am configuring 2 datasources with different session factory and different transaction managers. I am stuck with a problem here for @EnableTransactionManagement
annotation. I read in its documentation that,
这意味着我给方法的任何名称,它总是会搜索返回 PlatformTransactionManager
对象的方法,而我有2个transactionmanagers。现在的问题是,当我测试这个类时,它给了我错误:
This means whatever name I give to method, it will always search for the method which returns PlatformTransactionManager
object while I have 2 transactionmanagers. Now the problem is, when I test this class, it gives me error:
我甚至试图拥有2个不同的配置类但是徒劳无功。在xml配置中,情况并非如此。我在两个交易管理器上注册了两个< tx:annotation-driven transaction-manager =/>
标签,它运行正常。但是这里不能用注释做同样的事情。
I even tried to have 2 different Configuration classes but in vain. In xml configuration, this was not the case. I registered my both transaction managers with two <tx:annotation-driven transaction-manager="" />
tag and it worked fine. But not able to do same here with annotations.
如果我想在Spring注释配置类中配置2个具有2个不同事务管理器的数据源,我该怎么办?
What should I do if I want to configure 2 datasources with 2 different transaction managers in Spring annotated configuration class?
推荐答案
在配置类中,使用 @EnableTransactionManagement
注释。
In your configuration class, use @EnableTransactionManagement
annotation.
在此类中定义一个事务管理器:
Define a transaction manager in this class as:
@Bean(name="txName")
public HibernateTransactionManager txName() throws IOException{
HibernateTransactionManager txName= new HibernateTransactionManager();
txName.setSessionFactory(...);
txName.setDataSource(...);
return txName;
}
在您的类/方法中执行交易作业,注释如下:
There on, in your class/method that executes transactional job(s), annotate as follows:
@Transactional("txName")
或
@Transactional(value = "txName")
这就是如何将名称限定的事务管理器绑定到您需要的位置。您现在可以拥有任意数量的事务管理器,并根据需要随时使用它。
This is how you would tie a name qualified transaction manager to wherever you need it. You can now have as many transaction managers as you want and use it accordingly wherever you need.
这篇关于带有2个事务管理器的@EnableTransactionManagement注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!