@RefreshScope
It 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 Config
When managing configuration, how to refresh configuration issues in beans in real time when external configuration changes.
By using@RefreshScope
Note: Developers can avoid restarting the entire application, thereby improving application flexibility and dynamic adjustment capabilities.
In this article, I will introduce it in detail@RefreshScope
The 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?
@RefreshScope
is 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/refresh
Endpoint),@RefreshScope
The 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@RefreshScope
Annotation: 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
@RefreshScope
Automatically update data source connection information. -
Dynamically adjust log levels: When the log level or log output directory changes,
@RefreshScope
Refresh 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@RefreshScope
Note: 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
@RefreshScope
Usually with Spring@Component
or@Service
Use 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 thatAppConfig
BeanRefreshScope
Management, 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 onemessage
Configuration 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/refresh
The endpoint will fireAppConfig
Bean's refresh.
At this point, visit again/message
When 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/refresh
The endpoints need to dynamically refresh the configuration inor
Configure Actuator and expose it
refresh
Endpoint:
management: endpoints: web: exposure: include: refresh,env
This way it can passPOST
Request 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@RefreshScope
The marked bean.
3. How @RefreshScope works
3.1 Scope mechanism
In Spring,@RefreshScope
Implemented 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. -
@RefreshScope
Scope:and@Scope
Similar, but@RefreshScope
is a dynamic scope. when/refresh
When triggered, beans within that scope are destroyed and they are reloaded.
3.2 Reloading of dependency chains
quilt@RefreshScope
Annotation-managed beans and all their dependencies (other beans) will be reinitialized. This means that if a@RefreshScope
Bean is not@RefreshScope
Bean 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 UseContextRefresher
Trigger context refresh and reload all@RefreshScope
Managed beans. It works as follows:
- Listen to the configuration center changes: Spring Cloud Config pushes the latest configuration to the application when an external configuration changes are detected.
-
trigger
ContextRefresher
Context refresh:ContextRefresher
Is one of the core components of Spring Cloud Context for dynamically refreshing application contexts at runtime. -
Destroy and recreate Bean: Spring Cloud destroys all
@RefreshScope
Scoped beans and recreate them based on the latest configuration.
4. Things to note when using @RefreshScope
Although@RefreshScope
It 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
@RefreshScope
All beans in scope are destroyed and recreated when configuration changes.
if@RefreshScope
The 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
@RefreshScope
The 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
@RefreshScope
Scoped Beans and@Scope("singleton")
Or other scoped beans may have dependency conflicts.
because@RefreshScope
Beans are dynamically refreshed, so they depend on their non-@RefreshScope
A bean may get an invalid reference.
Solution:
- Try to ensure that
@RefreshScope
All dependencies related to beans are used by beans@RefreshScope
Manage to ensure that dependencies can be refreshed
Handle correctly.
4.3 Dependency chain issues with multiple @RefreshScope Beans
When multiple@RefreshScope
When beans are interdependent, if the refresh operation is not handled correctly, it may cause circular dependencies or bean initialization problems.
Solution:
- Avoid multiple
@RefreshScope
Direct 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,@RefreshScope
The 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
@RefreshScope
The life cycle and dependencies of the bean ensure the correctness of the refresh timing.
5. Best practices for @RefreshScope
-
Use only for beans that require dynamic refresh
@RefreshScope
Avoid using this annotation on all beans, as this can lead to application performance degradation.
-
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
/refresh
Operations are synchronized to all instances to ensure consistent configurations throughout the cluster. -
Monitor Bean Refresh Operation
Using Actuator provided
/refresh
Endpoints and/env
Endpoints monitor configuration refreshes to ensure that the application can correctly obtain the latest configuration information after configuration updates. -
Avoid direct dependency
@RefreshScope
BeanIf possible, use interfaces or abstract classes to reference
@RefreshScope
Beans to reduce the impact on dependency chains when beans are refreshed.
6. Summary
@RefreshScope
It 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@RefreshScope
and 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.