Ranjit Soni
Ranjit Soni

Reputation: 614

How can i use populated data in cache during server startup in Spring?


I am having problem while calling cacheable method from another cacheable method in Spring-4 application, please read following step for more clarification.
1) MyAppStartup class is called when server is started and it call convertXMLToObject method and store data in myInfo cache.
2) getFormList(String myId) method is called from some controller and ideally this method not invoke convertXMLToObject() method because in step-1, data already in cache but it is not working expected.
3) When second time getFormList(String myId) is called, it is not getting invoked and data is returned from cache i.e. cache is working fine for this method.

@Component
public class MyAppStartup {

    @Autowired
    private MyHelperClass myHelperClass;
    @EventListener(ContextRefreshedEvent.class)
    public void contextRefreshedEvent() throws Exception {
        logger.debug("Application Started :: Call to load XML information into Cache");
        myHelperClass.convertXMLToObject();
    } 
}
@Service
public class MyHelperClass {
    @Cacheable(value = "myInfoById", key = "{#myId}")
    public List<XMLFormData> getFormList(String myId){
        List<XMLFormData> xmlFormData = convertXMLToObject();
        return xmlFormData;
    }

    @Cacheable(value = "myInfo")
    public List<XMLFormData> convertXMLToObject() {
        //code to read xml and populate into java pojo class and return list
    }
}

//configuration in ehcache.xml
<cache name="myInfoById"
        eternal="false"
        overflowToDisk="false"
        maxEntriesLocalHeap="1000"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        memoryStoreEvictionPolicy="LRU" />

<cache name="myInfo"
        eternal="false"
        overflowToDisk="false"
        maxEntriesLocalHeap="1000"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        memoryStoreEvictionPolicy="LRU" />

Please help, Thanks in advance :)

Upvotes: 1

Views: 377

Answers (1)

Ranjit Soni
Ranjit Soni

Reputation: 614

I got the solution, instead of calling Cacheable method "convertXMLToObject()" from another Cacheable method "getFormList(String myId)", just call convertXMLToObject() method from place where method "getFormList(String myId)" is getting called and pass required data to method "getFormList(String myId)".

Upvotes: 1

Related Questions