Multiple Transaction Managers with @Transactional

原创
2014/11/10 11:21
阅读数 835

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====================

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部