Search code examples
javaspringspring-annotationstransactional

How to set annotation property/attribute programmatically?


So I need to set the timeout parameter for @Transactional annotation. This property will come from a property file which I'm not able to do since I'm encountering "The value for annotation attribute Transactional.timeout must be a constant expression". Something like this

@Value("${mytimeout}")
private int myTimeout;

@Transactional(timeout=myTimeout)
public void myMethod(){
}

The only time the timeout attribute can be set by a variable is when a variable is final.

So, I was thinking if it is possible to set the timeout property programmatically while using the @Transaction annotation. Or any other way I can set this attribute Thanks!


Solution

    • If you need the same timeout for all transactions, you can configure it as defaultTimeout in your transaction manager

    • Otherwise, you may try to play with custom AnnotationTransactionAttributeSource and TransactionAnnotationParser, though you'll need to replace <tx:annotation-drivern> with manual definition of corresponding beans in order to configure a custom attribute source.

      Then you can create a custom annotation and make TransactionAnnotationParser generate TransactionDefinition with custom timeout when it sees your annotation.

    • Otherwise, the easiest way to solve this problem is to give up using @Transactional and use TransactionTemplate instead.