@RefreshScope vs @ConfigurationProperties

Hits: 0

RefreshScope

@RefreshScope( [org.springframework.cloud.context.scope.refresh] ) is a special scope implementation provided by spring cloud, which is used to realize configuration and instance hot loading.

@RefreshScope implementation process

  1. Classes that need to be dynamically refreshed are marked with @RefreshScope annotation
  2. The @RefreshScope annotation annotates the @Scope annotation and defaults to the ScopedProxyMode.TARGET_CLASS; attribute. The function of this attribute is to create a proxy and use it to call the GenericScope get method to get the object each time it is called.
  3. If the property changes, it will call ContextRefresher refresh() – “RefreshScope refreshAll() to call the cache cleaning method, and send a refresh event notification -” GenericScope real cleaning method destroy() to clean up the cache
  4. The next time the object is used, the GenericScope get(String name, ObjectFactory<?> objectFactory) method will be called to create a new object and store it in the cache. At this time, the new object is a new property because of Spring’s assembly mechanism.

Client project adds dependencies

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Client project modification configuration file

#Show exposed access points 
management.endpoints.web.exposure.include =refresh,health,info

The client program adds support for refreshing annotations

@RestController 
//Refresh trigger address/actuator/refresh - post 
@RefreshScope 
public  class  ConfigTestController  {

    //The configuration information is read through the @Value annotation, and the configuration item is read with ${configuration item} 
    @Value ( "${test.config}" )
     private String configTest;

    @RequestMapping("/ConfigTest")
    public String ConfigTest(){
        return this.configTest;
    }
}

ConfigurationProperties

In the Spring Boot project, in order to meet the above requirements, we configure a large number of parameters in the application.properties or application.yml files. Through the [@ConfigurationProperties] annotation, we can easily obtain these parameter values.

test:
  auth:
    client:
      id: admin
      secret: admin123456

@Component
@ConfigurationProperties("test.auth.client")
@Getter
@Setter
public class AuthClientProp {

    /**
     * Authorization id
     */
    private String id;
    /**
     * Authorization key
     */
    private String secret;

}

At startup, the id and secret are automatically assigned to admin and admin123456.

You may also like...

Leave a Reply

Your email address will not be published.