dev333
dev333

Reputation: 799

How to reload the spring beans at runtime after hitting /actuator/refresh endpoint?

I'm trying to reload the spring bean by using the actuator refresh endpoint with the help of @RefreshScope annotation at bean level in spring boot 2.2.7 version.

But my HelloWorld bean is not getting refreshed by hitting the refresh endpoint. Can anyone please help me out ?

My main class:

@SpringBootApplication
public class SampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

}

HelloWorld:

public class HelloWorld {
    private String message;

       public void setMessage(String message){
          this.message  = message;
       }
       public void getMessage(){
          System.out.println("Your Message : " + message);
       }
    
}

ApplicationConfiguration:

@Configuration
public class ApplicationConfiguration {
    @Bean
    @RefreshScope
    public HelloWorld helloWorld() {
        System.out.println("From HelloWorld");
        return new HelloWorld();
    }
}

application.properties:

management.endpoints.web.exposure.include=*

Upvotes: 4

Views: 7392

Answers (1)

CryptoFool
CryptoFool

Reputation: 23079

Beans annotated with @RefreshScope aren't recreated right away. They are only recreated when one of their methods is called. This is true even when the app is first created. These beans are initialized "lazily" when they are first used.

If you are expecting "From Hello World" to be printed upon the call to "actuator/refresh", that won't happen right away. It won't happen until at least when something calls one of the methods on your HelloWorld bean.

Why I say "at least" is that the @RefreshScope thing is all about Spring re-injecting new properties into your beans via @Value annotations. I don't know why I think this, but I have a feeling that maybe your HelloWorld bean won't be rebuilt even when a method call is made on it because it has no @Value annotations. Spring may figure that because it has none of these, nothing will actually change in the bean, and so it won't be rebuilt. I'm not sure about this though.

To check this out, set up something that can be caused to use your HelloWorld bean during your app's normal execution. Then, after doing a refresh, you ought to see it rebuild and print "From Hello World" when it is accessed. If that doesn't happen, try injecting a property value into it with @Value and try again.

Upvotes: 2

Related Questions