Search code examples
javarestspring-bootspring-cache

Retrieving Data from Cache in Spring boot Cacheable


I want to implement two methods in service class. One method will take array of names as argument , will retrieve all its objects and store objects into cache.

@Cacheable(value="HeaderConfig")
public List<HeaderConfig> getHeadeConfigByFieldNames(String[] fieldNames)
{
    List<HeaderConfig> hcList = new ArrayList<HeaderConfig>();
    for (String fieldName : fieldNames) {
        hcList.add(headerConfigRepository.getHeadeConfigByFieldName(fieldName));
    }
    return hcList;
}

Another method will take name as an argument and it should fetch Object from cached record,that was done in previous method.

@Cacheable(value="HeaderConfig" , key ="#fieldName")
 public HeaderConfig getHeadeConfigByFieldName(String fieldName)
{
    System.out.println("from database");
    HeaderConfig hc = null;
    // CODE TO BE IMPLEMENTED TO GET DATA FROM CACHE
    return hc;
}

Please can anyone suggest how to process here. Do I need to configure any cache manager .


Solution

  • First method is not needed. Instead, the second method can be called in a loop. Spring will automatically take care of caching and retrieving.

    Just make sure that the second method is called on an autowired/Spring Injected instance of Bean in which it is implemented directly, Not through some method in the bean itself.