背景:
希望在springboot启动时加载一些数据到ECache缓存中,
@PostConstruct
@Cacheable(cacheNames = "cloudResourceVmTypeCache",key = "#root.methodName")
public List<Flavor> flavors(CloudCredential cloudCredential) {
//TODO something
return ""
}
测试后发现启动时运行过@PostConstruct方法但缓存并未生效
原因:
1、@PostConstruct阶段无法保证代理拦截器已经完全启动,对@Cacheable注解起不到拦截作用。
解决方案:
1、自定义一个监听事件监听ContextRefreshedEvent 或者 ApplicationReadyEvent
@Component
public class MyInitializer implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
//调用@Cacheable方法
}
}
参考: