Spring boot 为什么CachePut在本例中不起作用?

Spring boot 为什么CachePut在本例中不起作用?,spring-boot,spring-cache,spring-scheduled,Spring Boot,Spring Cache,Spring Scheduled,我正在使用Spring框架,希望从缓存中返回我的名字。5秒钟后,我将更新缓存,我希望收到一个新名称。。。。不幸的是,这不起作用。。。。为什么? @Component public class Test { public String name = "peter"; @Cacheable(value = "numCache") public String getName() { return name; } @Scheduled(fix

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

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

嗨,哈桑,是的,我是。。如果您正在使用
new
创建
Test
实例,我将更新我的示例。你需要自动连线。是的!!!现在它正在工作。。。。谢谢哈桑的帮助!嗨,哈桑,是的,我是。。如果您正在使用
new
创建
Test
实例,我将更新我的示例。你需要自动连线。是的!!!现在它正在工作。。。。谢谢哈桑的帮助!