Search code examples
spring-bootspring-cachespring-scheduled

Why does CachePut not work in this example?


I am playing around with the Spring framework and I would like to get my name returned from the cache. After 5 seconds I will update the cache and I hope to receive a new name.... unfortunately this is not working.... why?

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

}

Solution

  • You are creating an instance of Test yourself with new, you are not autowiring it. I would try like this:

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