2

In a spring boot application where I have two dataSources,

I need to select the proper dataSource using @Transactional annotation with the following parameters:

  • String value (required)
  • Boolean readOnly (default: false)

I want to create an @interface so I do not have to type the value (chances a developer make a mistake is motivating the decision)

So this needs to be written in a class :

@Transactional("transactionManager2") 

I have created the following @interface:

@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional("transactionManager2") public @interface TransactionManager2Tx { } 

This annotation replace @Transactional("transactionManager2") and it is working well.

However, I cannot pass the other parameters. For example, this is not possible:

@TransactionManager2Tx(readOnly = true) 

How can I achieve this?

1
  • See my next update =)) Commented Nov 3, 2017 at 15:38

1 Answer 1

1

Generally - that's not possible to do, because annotation's elements values are defined at compile-time. You can not dynamically pass the values there.

But, in Spring there is a tricky annotation type @AliasFor.

You can try do the following:

@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional("transactionManager2") public @interface TransactionManager2Tx { @AliasFor(annotation = Transactional.class, attribute = "readOnly") boolean readOnly() default false; } 

If it doesn't work, you can always define the two distinct annotations, kind of:

@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional(value = "transactionManager2", readOnly = true) public @interface ReadOnlyTransactionManager2Tx { } @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional(value = "transactionManager2", readOnly = false) public @interface NonReadOnlyTransactionManager2Tx { } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.