Spring @Transactional with timeoutString value from a configuration property bean

71 views Asked by At

We would like for specific methods to configure a different transaction timeout. Example:

@Data
@ConfigurationProperties("app.transactions")
public class TransactionProperties {
  private Duration myServiceTransactionTimeout = Duration.ofSeconds(5);
}

and annotate the service with:

@Service
public class MyService {

  @Transactional(timeoutString = "#{transactionProperties.myServiceTransactionTimeout.getSeconds()}")
  public Response exampleTransaction() {
     return doSomethingWithinTransaction();
  }

}

Unfortunately, the SpEL seems not to work. It turned out that Spring's AnnotationTransactionAttributeSource is implementing EmbeddedValueResolverAware, but there is no StringValueResolver assigned. Tested with Spring Boot 3.2.0.

Question: What do we need to change so that for methods transaction timeouts are configurable?

1

There are 1 answers

0
D. Kellenberger On

As far as we can see, full SpEL is not available here. The requirement can be achieved with an int instead of a Duration or Period object:

@Data
@ConfigurationProperties("app.transactions")
public class TransactionProperties {
  private int myServiceTransactionTimeoutInSeconds = 5;
}

and

@Service
public class MyService {

  @Transactional(timeoutString = "${app.transactions.myServiceTransactionTimeoutInSeconds}")
  public Response exampleTransaction() {
     return doSomethingWithinTransaction();
  }

}