我有一个固定超时的事务方法。是否可以通过application.yml
来配置事务超时?
@Transactional(propagation = Propagation.REQUIRED, timeout = TIMEOUT)
public String doStuff(String id) throws Exception {
service.doSomeStuff
}
答案 0 :(得分:1)
由于我们无法将变量值分配给Java注释属性,因此要以编程方式设置this.userList = [{_id: "test1", name: "test name"}];
的{{1}},最好的选择是覆盖@Transactional
。
假设您使用的是timeout
,则新管理器看起来像下面的代码。它允许设置每个事务的超时时间。我们可以使用AbstractPlatformTransactionManager#determineTimeout()
的名称来标识一个事务,对于Spring声明式事务,默认名称的格式为JpaTransactionManager
。
TransactionDefinition
然后配置FullyQualifiedClassName.MethodName
:
public class FooTransactionManager extends JpaTransactionManager {
private Map<String, Integer> txTimeout = new HashMap<String, Integer>();
public <T> void configureTxTimeout(Class<T> clazz, String methodName, Integer timeoutSecond) {
txTimeout.put(clazz.getName() + "." + methodName, timeoutSecond);
}
//The timeout set by `configureTxTimeout` will have higher priority than the one set in @Transactional
@Override
protected int determineTimeout(TransactionDefinition definition) {;
if (txTimeout.containsKey(definition.getName())) {
return txTimeout.get(definition.getName());
} else {
return super.determineTimeout(definition);
}
}
}
以上代码仅用于演示目的。实际上,您可以在配置过程中使用PlatformTransactionManager
从外部属性(例如@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final FooTransactionManager transactionManager = new FooTransactionManager();
transactionManager.setEntityManagerFactory(emf);
transactionManager.configureTxTimeout(Foo.class, "doStuff", 10);
transactionManager.configureTxTimeout(Bar.class, "doStuff", 20);
transactionManager.configureTxTimeout(Bar.class, "doMoreStuff", 30);
//blablabla
return transactionManager;
}
)中读取值。