AOP pointcut expression for specific annotated variable

1k views Asked by At

I have a scenario like this..

A custom annotation definition...

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheMe{
   String node();
}

User details class...

class User {
  String name;
  String ssn; 
}

And a class with "User" object as variable and uses @CacheMe annotation

Class Test{

   @CacheMe(node="user")
   User user;

   public User getUser(Long id){
       if(user != null){
       user = someImplementingClass.getUserDetails(id);
      }
      ....
      .....   
   }

}

I need pointcut expression when "user" object is verified for null or when user object is accessed. I'm using spring schema based AOP.

Thanks for your time.

1

There are 1 answers

1
José Carlos On

As pointed out in previous comments spring AOP does not support field level advices. The reason being of that is because Spring AOP uses proxies (at class or interface level, depending on the specific scenario). A proxy wraps an instance and is able to detect methods invocations. If you think about that, a wrapper can not detect property modifications, since a property can't be overriden at all, it can only be shadowed (from a java point of view).

With Spring AOP you'll be able to advice getters & setters, but if you need Field advises, then your only choice is AspectJ. (The same applies if you need to advise constructors and exception raises).

Check a quick aspectJ reference here and keep in mind if you go this path, you'll probably need to use these pointcuts:

  • get(Signature): every reference to any field matching Signature
  • set(Signature): every assignment to any field matching Signature. The assigned value can be exposed with an args pointcut

Additionally, if you decide to use aspectJ, you'll need to set up some things in your app, and decide if you prefer Load-time-weaving or Compile-Time-Weaving. That decision brings important consequences you'll probably want to keep in mind.