前言:在工作中需要实现动态刷新@Value字段值,但是项目使用的是Spring boot,又不想接入Nacos/Apollo等配置中心组件(额外增加成本),并且项目中只是简单的使用@Value读取一些配置信息进行使用(或者判断状态),所以写了简单的一个刷新机制,通过接口刷新@Value值,有需要的可以直接使用
一、自定义注解,用来需要修饰需要支持动态刷新的场景
import java.lang.annotation.*;
import java.lang.annotation.*;
/**
* @annotationName RefreshValue
* @description 自定义注解,用来需要修饰需要支持动态刷新的场景
**/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public home.php?mod=space&uid=593715 RefreshValue {
}
二、定义一个工具类实现配置转换
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @className RefreshEnvironment
* @description 定义一个工具类实现配置转换
**/
@Component
public class RefreshEnvironment implements EnvironmentAware {
private static ConfigurableEnvironment environment;
public static void updateValue(String key, Object newValue){
//自定的义配置文件名称
MutablePropertySources propertySources1 = environment.getPropertySources();
propertySources1.stream().forEach(x -> {
if (x instanceof MapPropertySource){
MapPropertySource propertySource = (MapPropertySource) x;
if (propertySource.containsProperty(key)){
String proname = propertySource.getName();
Map<String, Object> source = propertySource.getSource();
Map<String, Object> map = new HashMap<>(source.size());
map.putAll(source);
map.put(key, newValue);