Pointcuts for intercept assignment of annotated fi

2019-07-21 06:24发布

问题:

I'm writing a simple auditing framework which allows me to audit the fields of a class which are annotated with an @Audit annotation.

Example of possible annotations

class User {

    @Audit
    private String phoneNumber;

    private String name;

    @Audit
    public getName(){
        return name;
    };

    public setName(String name){
        this.name=name;
    }
}

So far I was only able to define a simple pointcut that watches calls to setters annotated with the @Audit annotation:

@Pointcut("call(* @Audit set*(*))")

How does a pointcut look that watches the assignment of fields that are annotated like in the above example?

回答1:

Unfortunately, it is not possible with SpringAOP at the moment,

Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans). Field interception is not implemented, although support for field interception could be added without breaking the core Spring AOP APIs. If you need to advise field access and update join points, consider a language such as AspectJ.

If You were to use AspectJ, you can use set(FieldPattern) pointcut. There are some examples in The AspectJTM 5 Development Kit Developer's Notebook

set(@Audit * *) seems to work, as for set(* @Audit * . *) - I'm not sure, perhaps AspectJ recognizes first wildcard as field modifiers but according to docs first element is annotation, second is modifier...



标签: java aspectj