How to load cache after application startup in spring boot ?

This article is written to explain how to perform any actions after the successful spring boot application startup, specifically here we are going to load few cache to make the application performance better as part of our server startup process.

Create “StartupEventListener” component as below:

This below class basically calls cacheservice and performs few cache loading process with ehcache as part of the server startup.

onApplicationReady -> Event listener gets called once the spring boot application has started successfully.

package com.ngdeveloper.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class StartupEventListener {

    private static final Logger logger = LoggerFactory.getLogger(StartupEventListener.class);

    @Autowired
    YourCacheService cacheService;

    @EventListener
    public void onApplicationReady(ApplicationReadyEvent ready) {
       // load cache either from cacheService or DAO layer directly here.
    }
}

Feel free to write your comments/thoughts below in the comments section.

Leave a Reply