为什么 CachePut 在此示例中不起作用?

Why does CachePut not work in this example?

我正在使用 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);
    }

}

您正在使用 new 创建 Test 的实例,您没有自动装配它。我会这样尝试:

@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());
        }
    }
}