3.7.2 Refreshable Scope

The Refreshable scope is a custom scope that allows a bean’s state to be refreshed via:

The following example illustrates @Refreshable scope behavior.

  1. @Refreshable (1)
  2. public static class WeatherService {
  3. private String forecast;
  4. @PostConstruct
  5. public void init() {
  6. forecast = "Scattered Clouds " + new SimpleDateFormat("dd/MMM/yy HH:mm:ss.SSS").format(new Date());(2)
  7. }
  8. public String latestForecast() {
  9. return forecast;
  10. }
  11. }
  1. @Refreshable (1)
  2. static class WeatherService {
  3. String forecast
  4. @PostConstruct
  5. void init() {
  6. forecast = "Scattered Clouds ${new SimpleDateFormat("dd/MMM/yy HH:mm:ss.SSS").format(new Date())}" (2)
  7. }
  8. String latestForecast() {
  9. return forecast
  10. }
  11. }
  1. @Refreshable (1)
  2. open class WeatherService {
  3. private var forecast: String? = null
  4. @PostConstruct
  5. fun init() {
  6. forecast = "Scattered Clouds " + SimpleDateFormat("dd/MMM/yy HH:mm:ss.SSS").format(Date())(2)
  7. }
  8. open fun latestForecast(): String? {
  9. return forecast
  10. }
  11. }
1The WeatherService is annotated with @Refreshable scope which stores an instance until a refresh event is triggered
2The value of the forecast property is set to a fixed value when the bean is created and won’t change until the bean is refreshed

If you invoke latestForecast() twice, you will see identical responses such as "Scattered Clouds 01/Feb/18 10:29.199".

When the /refresh endpoint is invoked or a RefreshEvent is published, the instance is invalidated and a new instance is created the next time the object is requested. For example:

  1. applicationContext.publishEvent(new RefreshEvent());
  1. applicationContext.publishEvent(new RefreshEvent())
  1. applicationContext.publishEvent(RefreshEvent())