Skip to content
Advertisement

Executing Spring AOP aspects for annotations aliased with @AliasFor

The idea is to create annotations hierarchy (similar to @Service, @Component etc) using @AliasFor annotation. This should give me the possibility to define aspect, that would execute on parent annotation, and every alias of it. But somehow it doesn’t work for me.

@ComponentScan is fine, @EnableAspectJAutoProxy is set.

Example:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ParentAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@ParentAnnotation
public @interface ChildAnnotation {

    @AliasFor(annotation = ParentAnnotation.class)
    String value() default "";
}
@Aspect
@Component
public class EventRecorderAspect {

    @Around("@annotation(com.example.ParentAnnotation)")
    public void exampleMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        // This should be executed for both @ParentAnnotation and @ChildAnnotation
    }
}
@RestController
public class ExampleController {
    @ChildAnnotation // This should result in executing aspect for every implementation
    String controllerMethod(); 
}

UPDATE: I’ve updated code, as @M.Deinum suggested in a comment below. But it still doesnt work.

Advertisement

Answer

AspectJ pointcut matching syntax, a subset of which is used by Spring AOP, is ignorant of meta annotations, even though withing the Spring framework as such there is support for it in other places. I think the closest you can get to specifying meta annotations in your pointcut is to do it explicitly up to the nesting level you require. See this answer for examples showing the syntax variants for both

  • class-level, e.g. within(@(@com.example.ParentAnnotation *) *),
  • method-level, e.g. execution(@(@com.example.ParentAnnotation *) * *(..))

annotations.


Update: @Ariel Grabijas asked in a follow-up comment:

So is there a way to somehow inherit annotations from interface method to class method?

Not in Java and also not by means of Spring AOP. But there is a workaround using native AspectJ inter-type definitions (ITD).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement