Spring boot preloading data from database in bean

吃可爱长大的小学妹 提交于 2019-12-04 15:21:04

A Cache would solve your requirement elegantly.

Ideally you would have a Service which has a method which returns the skills.

This method could looke like this:

import org.springframework.cache.annotation.Cacheable;

@Cacheable(value = "skills", key = "#root.methodName")
public List<Skill> getAllSkills() {
    return ... your skills ...;
}

To enable Caching in Spring Boot, add the @EnableCaching annotation to your configurations class, and add a Bean to configure it:

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;

@Bean
public CacheManager cacheManager() {
    return new ConcurrentMapCacheManager("skills", "othercachename");
}

This way, the method getAllSkills is just executed once, the first time it's called, and afterwards the values are returned from the cache-manager without even calling the method.

whistling_marmot

You can listen for the ApplicationReadyEvent, and then call the method (from @yglodt's answer) to initialise your cache.

Example code:

@Component
public class MyEventsListener {

    @Autowired
    SkillsService skillsService;

    @EventListener
    public void onApplicationReady(ApplicationReadyEvent ready) {
        skillsService.getAllSkills();
    }
}

Also remember that if you call getAllSkills() from within the SkillsService bean itself, you will not hit the cache, because the method is only advised when it is called on an injected proxy of the class.

If you're deploying the application as an executable jar (rather than a war file), then the simplest solution is to invoke the code that you want to run at start-up from your main method:

public class Application {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        SkillsService skillsService = context.getBean(SkillsService.class);
        skillsService.getAllSkills();
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!