Spring custom shortcut annotations with Meta-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.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Transactional("dbTransactionManager") public @interface DbTransaction { @AliasFor(annotation = Transactional.class) Isolation isolation() default Isolation.DEFAULT; @AliasFor(annotation = Transactional.class) Propagation propagation() default Propagation.REQUIRED; @AliasFor(annotation = Transactional.class) int timeout() default TransactionDefinition.TIMEOUT_DEFAULT; @AliasFor(annotation = Transactional.class) boolean readOnly() default false; @AliasFor(annotation = Transactional.class) Class<? extends Throwable>[] rollbackFor() default {}; @AliasFor(annotation = Transactional.class) String[] rollbackForClassName() default {}; @AliasFor(annotation = Transactional.class) Class<? extends Throwable>[] noRollbackFor() default {}; @AliasFor(annotation = Transactional.class) String[] noRollbackForClassName() default {}; }
allows us to write the example from the previous section as
public class TransactionalService { @DbTransaction public void setSomething(String name) { ... } @DbTransaction(readOnly=true) public void readSomething() { ... } }
As you can see meta-annotations can be combined to create composed annotations. In addition, composed annotations may optionally redeclare attributes from meta-annotations to allow user customization. This can be particularly useful when you want to only expose a subset of the meta-annotation’s attributes. For example, Spring’s @Transactional annotation hardcodes the transactionManager but still allows customization of the other attributes.
References
- https://docs.spring.io/spring/docs/5.0.6.RELEASE/spring-framework-reference/data-access.html#tx-custom-attributes
- https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-meta-annotations