spring aop - How do we implement method cache in java -


i'd design own annotation in order cache results retrieved earlier database call.

for example:

public class countryservice {  @methodcache  public list<country> getcountries();   @methodcache  public country getcountrybyid(int countryid);   @invalidatemethodcache  public country getcountrybyid(int countryid);  } 

i want use type of annotation more/all of methods. need implement type of annotation?

@methodcache: cache method result.
@invalidatemethodcache: clear cache.

a solution when using spring-aop create aspect handle methods annotated custom annotation. crude implementation this:

map<string, object> methodcache = new hahsmap<>();  @around("execution(@(@com.mypack.methodcache *) *)") public object cachemethod(proceedingjoinpoint pjp) {      string cachekey = getcachekey(pjp);      if ( methodcache.get(cachekey)) {           return methodcache.get(cachekey);      } else {           object result = pjp.proceed();           methodcache.put(cachekey, result);           return result;      } }  private string getcachekey(proceedingjoinpoint pjp) {      return pjp.getsignature().tostring() + pjp.gettarget() + arrays.aslist(pjp.getargs()); } 

Comments