Search code examples
javaannotationsspring-annotations

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 {

}

Solution

  • 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 {
    }