java - Custom Key Generation in Spring Caching -
i have started working on spring caching.
this class in have implemented caching:
@cacheconfig(cachenames="empcache") public class general { @cacheable public string getdetails(int empid) { if(empid==1) { system.out.println("inside getdetails. emp id 1."); return "amar"; } else { system.out.println("emp id not 1."); return "anthony"; } } }
this custom bean user key generation:
@component public class temp { private string name; private string surname; public string getname() { return name; } public void setname(string name) { this.name = name; } public string getsurname() { return surname; } public void setsurname(string surname) { this.surname = surname; } }
my context.xml
<context:component-scan base-package="com.packages.beans" /> <cache:annotation-driven key-generator="enhanceddefaultkeygenerator"/> <bean id ="enhanceddefaultkeygenerator" class="com.packages.beans.mykeygenerator"/> <bean id="cachemanager" class="org.springframework.cache.ehcache.ehcachecachemanager" p:cache-manager-ref="ehcache"/> <bean id="ehcache" class="org.springframework.cache.ehcache.ehcachemanagerfactorybean" p:config-location="classpath:ehcache.xml" p:shared="true"/>
below custom key generation class:
public class mykeygenerator implements keygenerator { @autowired private temp temp1; @override public object generate(object arg0, method arg1, object... arg2) { string key = temp1.getname() + temp1.getsurname() + "_" + arg1.getname(); system.out.println("key "+key); return key; } }
main method:
public static void main(string args[]) { temp generate=new temp(); generate.setname("abc"); generate.setsurname("def"); applicationcontext context = new classpathxmlapplicationcontext("context.xml"); general main=(general) context.getbean("mybean"); system.out.println(main.getdetails(main.getempid())); }
when running program main method setting the value of temp in it. getting key in keygenerator class null_null_getdetails , not abc_def_getdetails.
but need key composed of values prefill in custom bean temp.
the 'temp' creating in main not part of spring context. instead spring creates bean 'temp' from
@component public class temp
but there name , surename null. instance of temp used keygenerator , that's why nulls in key.
you must create bean of temp set name , surname. in java config can :
@bean temp temp() { temp generate=new temp(); generate.setname("abc"); generate.setsurname("def"); return temp; }
Comments
Post a Comment