我正在使用Spring框架,我想从缓存中返回我的名字。 5秒钟后,我将更新缓存,并希望收到一个新名称。...很遗憾,这无法正常工作。...为什么?
@Component
public class Test {
public String name = "peter";
@Cacheable(value = "numCache")
public String getName() {
return name;
}
@Scheduled(fixedRate = 5000)
@CachePut(value = "numCache")
public String setName() {
this.name = "piet";
return name;
}
}
@Component
public class AppRunner implements CommandLineRunner {
public void run(String... args) throws Exception {
Test test = new Test();
while(true) {
Thread.sleep(1000);
System.out.println(test.getName());
}
}
}
@SpringBootApplication
@EnableCaching
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
答案 0 :(得分:1)
您正在使用Test
自己创建new
的实例,而不是自动装配。我会这样尝试:
@Component
public class Test {
public String name = "peter";
@Cacheable(value = "numCache")
public String getName() {
return name;
}
@Scheduled(fixedRate = 5000)
@CachePut(value = "numCache")
public String setName() {
this.name = "piet";
return name;
}
}
@Component
public class AppRunner implements CommandLineRunner {
@Autowired private Test test;
public void run(String... args) throws Exception {
while(true) {
Thread.sleep(1000);
System.out.println(test.getName());
}
}
}