gpt4 book ai didi

java - 用 @Cacheable 注释的方法不会被拦截

转载 作者:行者123 更新时间:2023-11-30 02:49:49 24 4
gpt4 key购买 nike

我是 Spring 缓存的新手。我在我的 maven pom 中使用 spring-boot-starter-1.4.0.RELEASE 。据我了解的文档,如果我采取这样的事情:

@Configuration
@EnableCaching
public class TestApplication {
@Bean
public CacheManager cacheManager() {
// configure and return an implementation of Spring's CacheManager SPI
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("default")));
return cacheManager;
}

@Bean
public MyService myService() {
// configure and return a class having @Cacheable methods
return new MyService();
}

public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(TestConfiguration.class);
MyService ms = ctx.getBean(MyService.class);
ms.doCacheableOperation(); // calls the underlying method
ms.doCacheableOperation(); // SHOULD just consult the cache
}
}

并有一个这样的类:

public class MyService {
@Cacheable
public String doCacheableOperation() {
System.out.println("======================CALLING EXPENSIVE METHOD=======================");
return "done";
}
}

当 main 方法在 TestApplication 中运行时,对 MyServce#doCacheableOperation 的第一次调用应该输出到屏幕,但第二次调用不应输出到屏幕,因为结果将从第一次开始被缓存。然而,事实并非如此。输出显示两次。

配置代码取自 EnableCaching 的 Javadoc:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/EnableCaching.html

让我困惑的一件事是,当我调试和检查 MyService 的实例时,它只是原始对象,没有包装在任何 CGLib 子类等中。

我需要如何更改配置/方法才能缓存 MyService#doCacheableOperation 的结果?

最佳答案

哦, child 。找到了。我发送到 SpringApplication#run 的类中有一个简单的拼写错误:

SpringApplication.run(TestConfiguration.class)

应该是

SpringApplication.run(TestApplication.class)

现在一切似乎都井然有序!

关于java - 用 @Cacheable 注释的方法不会被拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39047139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com