Multiple Transaction Managers with @Transactional

http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/transaction.html

Multiple Transaction Managers with @Transactional

Multiple Transaction Managers with @Transactional

Most Spring applications only need a single transaction manager, but there may be situations where you want multiple independent transaction managers in a single application. The value attribute of the @Transactional annotation can be used to optionally specify the identity of the PlatformTransactionManager to be used. This can either be the bean name or the qualifier value of the transaction manager bean. For example, using the qualifier notation, the following Java code

public class TransactionalService {
    @Transactional("order")
    public void setSomething(String name) { ... }
    @Transactional("account")
    public void doSomething() { ... }
}

 

could be combined with the following transaction manager bean declarations in the application context.

<tx:annotation-driven />
<bean id="transactionManager1"
	class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	...
	<qualifier value="order" />
</bean>
<bean id="transactionManager2"
	class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	...
	<qualifier value="account" />
</bean>

In this case, the two methods on TransactionalService will run under separate transaction managers, differentiated by the "order" and "account" qualifiers. The default <tx:annotation-driven> target bean name transactionManager will still be used if no specifically qualified PlatformTransactionManager bean is found.

 

Custom shortcut annotations

If you find you are repeatedly using the same attributes with @Transactional on many different methods, then Spring’s meta-annotation support allows you to define custom shortcut annotations for your specific use cases. For example, defining the following annotations

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("order")
public @interface OrderTx {
}

 

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("account")
public @interface AccountTx {
}

allows us to write the example from the previous section as

public class TransactionalService {
    @OrderTx
    public void setSomething(String name) { ... }
    @AccountTx
    public void doSomething() { ... }
}

Here we have used the syntax to define the transaction manager qualifier, but could also have included propagation behavior, rollback rules, timeouts etc.

====================END====================

转载于:https://my.oschina.net/xinxingegeya/blog/342624

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值