Search code examples
javaspringaopspring-aop

Is it possible to compose AOP annotations?


So, I have 2 annotation A and B coming from existing java libraries and that implement AOP.

Both of them do something that is necessary to my class and I need to put them in this order (A before B):

public class MyClass{

    @A(parameter="par")
    @B(value="key")
    public void method(){

    }
}

Would it be possible to define a 3rd annotation, C, as a composition of both? So in the end I would get:

public class MyClass{

    @C(parameter="par", value="key")
    public void method(){

    }
}

edit: added the requirement of taking a parameter from @A as well and the fact that I don't have the source code as the annotations are taken from libs.


Solution

  • It depends on library you use. for example spring does

     @Documented
       @Inherited
        @SpringBootConfiguration
        @EnableAutoConfiguration
        @ComponentScan(excludeFilters = {
                @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
                @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
        public @interface SpringBootApplication {
    
            /**
             * Exclude specific auto-configuration classes such that they will never be applied.
             * @return the classes to exclude
             */
            @AliasFor(annotation = EnableAutoConfiguration.class)
            Class<?>[] exclude() default {};
    

    with this approach you would have:

        @A
        @B
        public @interface C{
            @AliasFor(annotation = B.class)
            String value();
            @AliasFor(annotation = А.class, attribute = "parameter")
            String param();
        }