[英]Spring Cache not working as a compute property
我想使用一種機制來創建一次性計算 function。 我嘗試使用 Spring 緩存。 但它不起作用。 請幫我解決這個問題。 我的代碼如下,
Gradle 依賴
compile 'org.springframework.boot:spring-boot-starter-cache'
Spring 引導應用程序的主要 Class
@SpringBootApplication
@EnableCaching
public class Application {
public static ApplicationContext applicationContext;
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// todo: Try to save response text and request body
applicationContext = SpringApplication.run(Application.class, args);
}
@Bean
WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("classpath:/")
.setCacheControl(CacheControl.maxAge(3600, TimeUnit.SECONDS).noTransform().mustRevalidate());
}
};
}
}
我的計算屬性和測試方法
public String test(){
return hello();
}
@Cacheable("hello")
public String hello(){
System.out.println("hello");
return "Hello";
}
@Cacheable 注釋在從 @Bean 外部調用它時緩存值,因此從 bean 內部的另一個方法調用它將不起作用。
嘗試類似的東西
@Bean
public class CachingBean {
@Cacheable("hello")
public String hello(){
System.out.println("hello");
return "Hello";
}
}
@Service
public class CallerService {
@Autowired
private CachingBean cachingBean;
// Setters, constructors...
public String test(){
return cachingBean.hello();
}
}
然后它應該工作。 這是因為 @Cacheable 注解在作為 Bean 注入時圍繞方法調用創建了一個代理,因此不會攔截直接調用(對直接創建的實例)或內部調用,並且緩存機制甚至看不到這些調用。
我仍然有時會忘記它並在一開始就被它咬住:)。 干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.