Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring AOP: @annotation(annotation)

I am (of course) trying to maintain a project using many constructs I don't know that well. In the course of attempting to figure out the AOP use within Spring, I came across methods with the following annotation:

@Around(value = "@annotation(annotation)")

So @Around means we're doing the 'around' version of the method pointcut in AOP, I understand that. I don't know what the other part means. The Spring documentation gives the following:

@annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation

I don't know what that means - "method being executed in Spring AOP" sounds like the advised method, but I don't know how I (or Spring) figure out which methods are being advised. It sounds like it is the methods that have "the given annotation", but if so, what annotation has been given?

What methods are advised by this annotation? And what else does it mean?

like image 251
arcy Avatar asked Feb 05 '14 21:02

arcy


2 Answers

if you have the following Spring Bean:

@Component
public class foo {

    @com.pkg.Bar      
    void fooMe() {
    }
}

Then the following Advice:

@Around("@annotation(com.pkg.Bar)")

Will invoke the interceptor around fooMe (or any other Spring bean method annotated with @Bar)

The @Transactional annotation is a good example

like image 50
Ori Dar Avatar answered Oct 25 '22 02:10

Ori Dar


You would have a parameter named annotation, of the appropriate type. It's called bound annotation, see this excerpt from the Spring AOP documentation:

The following example shows how you could match the execution of methods annotated with an @Auditable annotation, and extract the audit code.

First the definition of the @Auditable annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auditable {
    AuditCode value();
}

And then the advice that matches the execution of @Auditable methods:

@Before("com.xyz.lib.Pointcuts.anyPublicMethod() && @annotation(auditable)")
public void audit(Auditable auditable) {
    AuditCode code = auditable.value();
    // ...
}
like image 29
Sergej Koščejev Avatar answered Oct 25 '22 02:10

Sergej Koščejev