Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring custom annotation: how to inherit attributes?

I am creating my own custom shortcut annotation, as described in Spring Documentation:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(value = "Custom", readOnly = true)
public @interface CustomTransactional {
}

Is it possible, that with my custom annotation I could be also able to set any other attributes, which are available in @Transactional? I would like to able use my annotation, for example, like this:

@CustomTransactional(propagation = Propagation.REQUIRED)
public class MyClass {

}
like image 996
Laimoncijus Avatar asked Jan 04 '13 09:01

Laimoncijus


People also ask

Can annotation be inherited?

Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it.

Are Spring annotations inherited?

Annotations on methods are not inherited by default, so we need to handle this explicitly.

What is @interface annotation in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.

What is the annotation used to define attributes for an element?

We can also explicitly specify the attributes in a @Test annotation. Test attributes are the test specific, and they are specified at the right next to the @Test annotation.


Video Answer


1 Answers

No, that will not work, if you want additional attributes that will have to be set on your custom annotation itself this way:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(value = "Custom", readOnly = true, propagation = Propagation.REQUIRED)
public @interface CustomTransactional {
}

A solution (bad one :-) ) could be to define multiple annotations with the base set of cases that you see for your scenario:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(value = "Custom", readOnly = true, propagation = Propagation.REQUIRED)
public @interface CustomTransactionalWithRequired {
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(value = "Custom", readOnly = true, propagation = Propagation.SUPPORTED)
public @interface CustomTransactionalWithSupported {
}
like image 104
Biju Kunjummen Avatar answered Sep 28 '22 04:09

Biju Kunjummen