title: Custom Key Generation in Spring Caching
body: <p>I just have started working on Spring caching.</p>
  
  <p>This is the class in which I have implemented caching:</p>
  
  <pre><code>@CacheConfig(cacheNames="empcache")
  public class General {  
  
      @Cacheable
      public String getDetails(int empId) {
  
          if(empId==1) {
              System.out.println("Inside getDetails. Emp id is 1.");
              return "Amar";
          } else {
              System.out.println("Emp id is not 1.");
              return "Anthony";
          }
      }
  }
  </code></pre>
  
  <p>This is a custom bean which I will user for Key Generation:</p>
  
  <pre><code>@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;
      }   
  }
  </code></pre>
  
  <p>My context.xml</p>
  
  <pre><code>&lt;context:component-scan base-package="com.packages.beans" /&gt;
  &lt;cache:annotation-driven key-generator="enhancedDefaultKeyGenerator"/&gt;
  
  &lt;bean id ="enhancedDefaultKeyGenerator" class="com.packages.beans.myKeyGenerator"/&gt;
  
  &lt;bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" 
                          p:cache-manager-ref="ehcache"/&gt;
  
  &lt;bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
                          p:config-location="classpath:ehcache.xml" p:shared="true"/&gt;
  </code></pre>
  
  <p>Below is the custom key Generation class:</p>
  
  <pre><code>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 is "+key);
  
          return key;
      }   
  }
  </code></pre>
  
  <p>Main Method:</p>
  
  <pre><code>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()));
  }
  </code></pre>
  
  <p>When I am running the program from the main method setting the the value of temp in it. I am getting the key in keyGenerator class as null_null_getDetails and not as ABC_DEF_getDetails. </p>
  
  <p>But I need the key to be composed of the values that I prefill in the custom bean temp.</p>