java动态刷新@Value

前言:在工作中需要实现动态刷新@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);
          
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值