【问题标题】:@CachePut does not work in @Configuration for pre cache@CachePut 在预缓存的 @Configuration 中不起作用
【发布时间】:2016-09-21 15:44:26
【问题描述】:

我试图在 spring boot 1.3.5 中使用 spring stater-cache,除了 @Configuration 类中的预加载缓存外一切正常。

Failed tests:
  CacheTest.testCacheFromConfig: expected:<n[eal]> but was:<n[ot cached]>

请看下面的代码,如果你以前遇到过,请与我分享:)

@Component
public class CacheObject{

    @CachePut(value = "nameCache", key = "#userId")
    public String setName(long userId, String name) {
        return name;
    }

    @Cacheable(value = "nameCache", key = "#userId")
    public String getName(long userId) {
        return "not cached";
    }

}

@Component
public class CacheReference {

    @Autowired
    private CacheObject cacheObject;

    public String getNameOut(long userId){
        return cacheObject.getName(userId);
    }
}

@Configuration
public class SystemConfig {

    @Autowired
    private CacheObject cacheObject;

    @PostConstruct
    public void init(){
        System.out.println("------------------");
        System.out.println("-- PRE LOAD CACHE BUT DIDN'T GET CACHED");
        System.out.println("------------------");

        cacheObject.setName(2, "neal");
        cacheObject.setName(3, "dora");

    }

}

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BootElastic.class)
@WebAppConfiguration
public class CacheTest {

    @Autowired
    private CacheObject cacheObject;
    @Autowired
    private CacheReference cacheReference;

    @Test
    public void testCache(){

        String name = "this is neal for cache test";
        long userId = 1;

        cacheObject.setName(userId, name);
//        cacheObject.setName(2, "neal"); // this will make test success
        String nameFromCache = cacheReference.getNameOut(userId);
        System.out.println("1" + nameFromCache);
        Assert.assertEquals(nameFromCache, name);

    }

    @Test
    public void testCacheFromConfig(){
        String nameFromCache = cacheReference.getNameOut(2);
        System.out.println("4" + nameFromCache);
        Assert.assertEquals(nameFromCache, "neal");
    }
}

【问题讨论】:

    标签: spring caching


    【解决方案1】:

    @PostConstruct 方法在所有 postProcessBeforeInitialization() BeanPostProcessor 方法被调用之后,并且在 postProcessAfterInitialization() 被调用之前被调用。所以在bean周围有任何代理之前调用它,包括一个,将值放入缓存。 与您不能在 @PostConstruct 中使用 @Transactional 或 @Async 方法的原因相同。

    您可以从 ContextRefreshedEvent 上的某个 @EventListener 调用它以使其正常工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多