SoFunction
Updated on 2025-04-05

@RefreshScope annotation and usage scenarios in SpringCloud

@RefreshScopeIt is one of the important notes in Spring Cloud for dynamic refreshing bean configuration.

It is mainly used to solve the problem of passing in Spring Cloud projectsSpring Cloud ConfigWhen managing configuration, how to refresh configuration issues in beans in real time when external configuration changes.

By using@RefreshScopeNote: Developers can avoid restarting the entire application, thereby improving application flexibility and dynamic adjustment capabilities.

In this article, I will introduce it in detail@RefreshScopeThe usage scenarios, configuration methods, principles and possible problems, combined with specific code examples, help everyone to deeply understand the function and usage of this annotation.

1. Introduction to @RefreshScope

1.1 What is @RefreshScope?

@RefreshScopeis an annotation provided by Spring Cloud Context, which is used to identify a refreshed scope in Spring applications (Refresh Scope) managed beans.

This annotation can be achieved when we use Spring Cloud Config or other external configuration centersDynamic refresh configurationfunction.

Specifically, when the external configuration changes, we only need to trigger the refresh operation (by calling/actuator/refreshEndpoint),@RefreshScopeThe managed bean will reload the latest configuration, and the updated value will be automatically obtained where the bean is used in the application.

1.2 Use scenarios

In microservice architectures, configuration centers, such as Spring Cloud Config, are often used to centrally manage the configuration of individual microservices.

In some scenarios, external configurations (such as database connection parameters, API keys, service addresses, etc.) may change dynamically without wishing to take effect by restarting the service.

pass@RefreshScopeAnnotation: You can dynamically refresh the properties of certain beans without restarting the application.

Here are some common usage scenarios:

  • Dynamically update database connection information: When the database URL, username, password and other configuration information are changed in the configuration center, you can use it@RefreshScopeAutomatically update data source connection information.
  • Dynamically adjust log levels: When the log level or log output directory changes,@RefreshScopeRefresh the log configuration bean for immediate effect.
  • Dynamically switch external API service addresses: When the URL address of an external service changes, the configuration of the service call can be automatically updated through this annotation.

2. Use of @RefreshScope

2.1 Introducing related dependencies

To use@RefreshScopeNote: First, you need to introduce Spring Cloud related dependencies into the project and ensure that Spring Cloud Config is used in the project.

The following is a typical oneConfiguration:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Cloud Starter Config -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>

    <!-- Spring Boot Actuator (supply /refresh Endpoint) -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

2.2 Using @RefreshScope in Beans

@RefreshScopeUsually with Spring@Componentor@ServiceUse annotations together to indicate that the bean is managed by refresh scope.

When the external configuration changes, Spring reinstages the bean and injects the latest configuration.

Here is a simple example:

2.2.1 Reading Beans for External Configuration Files

package ;

import ;
import ;
import ;

@Component
@RefreshScope
public class AppConfig {

    @Value("${:Default message}")
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
         = message;
    }
}
  • @RefreshScope: means thatAppConfigBeanRefreshScopeManagement, will automatically refresh when external configuration changes.
  • @Value("${:Default message}"): Read from the configuration centerThe value of the default value is used if the configuration does not exist."Default message"

2.2.2 Using configuration beans in the controller

Create a simple REST controller to display the current onemessageConfiguration information:

package ;

import ;
import ;
import ;

@RestController
public class ConfigController {

    private final AppConfig appConfig;

    public ConfigController(AppConfig appConfig) {
         = appConfig;
    }

    @GetMapping("/message")
    public String getMessage() {
        return ();
    }
}

In this example,When the value of/actuator/refreshThe endpoint will fireAppConfigBean's refresh.

At this point, visit again/messageWhen interface, you will see updated configuration information.

2.3 Enable Actuator and expose the /refresh endpoint

In order to be able to use the provided by Spring Cloud/refreshThe endpoints need to dynamically refresh the configuration inorConfigure Actuator and expose itrefreshEndpoint:

management:
  endpoints:
    web:
      exposure:
        include: refresh,env

This way it can passPOSTRequest to trigger the refresh operation:

curl -X POST http://localhost:8080/actuator/refresh

After executing this command, Spring Cloud scans the configuration center and reloads all@RefreshScopeThe marked bean.

3. How @RefreshScope works

3.1 Scope mechanism

In Spring,@RefreshScopeImplemented a customScope, calledRefreshScope. When the configuration changes, Spring Cloud Context destroys all beans in the current scope and reinstages the beans with the new configuration.

  • Default scope: Singleton Scope: By default, all beans in Spring are singletons (@Scope("singleton")), i.e. there is only one instance in the entire Spring container.
  • @RefreshScopeScope:and@ScopeSimilar, but@RefreshScopeis a dynamic scope. when/refreshWhen triggered, beans within that scope are destroyed and they are reloaded.

3.2 Reloading of dependency chains

quilt@RefreshScopeAnnotation-managed beans and all their dependencies (other beans) will be reinitialized. This means that if a@RefreshScopeBean is not@RefreshScopeBean references, then update configurations may cause unrefresh scope management beans that are not managed in the refreshed scope to fail or fail to obtain the latest configuration information.

3.3 Configuration Center and ContextRefresher

Spring Cloud Config UseContextRefresherTrigger context refresh and reload all@RefreshScopeManaged beans. It works as follows:

  1. Listen to the configuration center changes: Spring Cloud Config pushes the latest configuration to the application when an external configuration changes are detected.
  2. triggerContextRefresher Context refreshContextRefresherIs one of the core components of Spring Cloud Context for dynamically refreshing application contexts at runtime.
  3. Destroy and recreate Bean: Spring Cloud destroys all@RefreshScopeScoped beans and recreate them based on the latest configuration.

4. Things to note when using @RefreshScope

Although@RefreshScopeIt provides a very convenient configuration dynamic refresh function, but the following issues need to be paid attention to when using it:

4.1 Memory consumption and performance issues

@RefreshScopeAll beans in scope are destroyed and recreated when configuration changes.

if@RefreshScopeThe large number of beans managed or the high initialization cost of these beans may lead to increased memory consumption and affect application performance.

Solution:

  • Choose to use with caution@RefreshScopeThe beans, use this annotation only for those beans that do require dynamic refresh.
  • Monitor performance overhead through tests and try to avoid using it in frequently changing scenarios@RefreshScope

4.2 Bean dependency issues

@RefreshScopeScoped Beans and@Scope("singleton")Or other scoped beans may have dependency conflicts.

because@RefreshScopeBeans are dynamically refreshed, so they depend on their non-@RefreshScopeA bean may get an invalid reference.

Solution:

  • Try to ensure that@RefreshScopeAll dependencies related to beans are used by beans@RefreshScopeManage to ensure that dependencies can be refreshed

Handle correctly.

4.3 Dependency chain issues with multiple @RefreshScope Beans

When multiple@RefreshScopeWhen beans are interdependent, if the refresh operation is not handled correctly, it may cause circular dependencies or bean initialization problems.

Solution:

  • Avoid multiple@RefreshScopeDirect dependency between beans, using a finer granular configuration refresh strategy.

4.4 Risks of Integration with Spring Cloud Bus

When using Spring Cloud Bus for configuration refresh,@RefreshScopeThe dependency chain of beans may be affected by the message bus, resulting in inconsistent refresh order or dependencies.

Solution:

  • Special attention is required when using Spring Cloud Bus@RefreshScopeThe life cycle and dependencies of the bean ensure the correctness of the refresh timing.

5. Best practices for @RefreshScope

  1. Use only for beans that require dynamic refresh@RefreshScope

    Avoid using this annotation on all beans, as this can lead to application performance degradation.

  2. Use Spring Cloud Bus for global refresh in a cluster environment

    If the application is deployed in a cluster environment, you can use Spring Cloud Bus to/refreshOperations are synchronized to all instances to ensure consistent configurations throughout the cluster.

  3. Monitor Bean Refresh Operation

    Using Actuator provided/refreshEndpoints and/envEndpoints monitor configuration refreshes to ensure that the application can correctly obtain the latest configuration information after configuration updates.

  4. Avoid direct dependency@RefreshScope Bean

    If possible, use interfaces or abstract classes to reference@RefreshScopeBeans to reduce the impact on dependency chains when beans are refreshed.

6. Summary

@RefreshScopeIt is a very powerful annotation in Spring Cloud that can help developers dynamically refresh configurations without restarting the application.

When using this annotation, it is crucial to understand how it works, lifecycle management, and dependency handling.

I hope that through the detailed analysis of this article, everyone can better understand it@RefreshScopeand flexibly apply it in actual projects, thereby improving the dynamic configuration management capabilities of microservice applications.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.