问题
Prior to Spring Boot, one was able to globally say (without having to identify on each @Transactional element) that all checked exceptions should roll back a transaction:
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" rollback-for="Exception" timeout="20"/>
</tx:attributes>
</tx:advice>
How is the above achieved via Java config in the Spring Boot world?
回答1:
Use custom 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(rollbackFor=Exception.class)
public @interface OrderTx {
}
https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#tx-custom-attributes
来源:https://stackoverflow.com/questions/47838868/spring-boot-transaction-manager-advice-to-roll-back-all-exceptions