简体   繁体   中英

Loading data from database during application startup

There is a table in DB(Oracle) which stores "code" and its "Description". I need to load this table data during my application startup and store it in a variable (probably a Map object) so that I can look up the description of the code for each request without hitting the DB for every request. What would be the best way to do this?

Application is a standalone Java application based on Spring framework.

Thanks.

Im not sure, but Spring events might help. For example, you can use ContextRefreshedEvent - this event is published whenever the Spring Context is started or refreshed.

Please check: running-code-on-spring-boot-startup or better-application-events-in-spring-framework-4-2

You can create a class that picks application startup method. In spring you can implement ApplicationListener interface with ApplicationReadyEvent event.

At this point your application is ready to communicate with database and will execute your code automatically.

@Component
public class AppBootstrapListener implements ApplicationListener<ApplicationReadyEvent> {

    //Inject Service or repository if you have.

    /**
    * Executes on application ready event
    * Check's if data exists & calls to create or read data
    */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // code here
    }

}

For any clearification add a comment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM