@PostConstruct与@Cacheable组合使用缓存失效

背景:

希望在springboot启动时加载一些数据到ECache缓存中,

@PostConstruct
@Cacheable(cacheNames = "cloudResourceVmTypeCache",key = "#root.methodName")
public List flavors(CloudCredential cloudCredential) {
    //TODO something
    return ""

}

测试后发现启动时运行过@PostConstruct方法但缓存并未生效

原因:

        1、@PostConstruct阶段无法保证代理拦截器已经完全启动,对@Cacheable注解起不到拦截作用。

解决方案:

        1、自定义一个监听事件监听ContextRefreshedEvent 或者 ApplicationReadyEvent

@Component
public class MyInitializer implements ApplicationListener {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        //调用@Cacheable方法
    }
}

参考:

https://stackoverflow.com/questions/28350082/spring-cache-using-cacheable-during-postconstruct-does-not-work

https://stackoverflow.com/questions/28350082/spring-cache-using-cacheable-during-postconstruct-does-not-work

你可能感兴趣的:(@Cacheable,@PostConstruct)