springboot解析复杂配置

在springboot项目开发过程中经常需要定义一些复杂配置,且该配置还可以动态扩展,现在介绍一种复杂配置加载方式,如下面的配置:

system:
  scenes: aaaa,bbbb
  aaaa:
    name: "场景1"
    sql: "select * from tableA"
    keys:
      - "11:22"
      - "11:22"
  bbbb:
    name: "场景2"
    sql: "select * from tableB"
    keys:
      - "device:device"
      - "mba:mba"

如果配置是这样,则可以定义一个key的字符串列表

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 */
@Slf4j
@Configuration
@RefreshScope
@Data
public class SceneConfig implements EnvironmentAware {
    @Value("${system.scenes}")
    private String scenesPrefixs;

    private ConcurrentHashMap<String,SceneProperties> sceneConfig=new ConcurrentHashMap<>();

    public SceneProperties getSceneProperties(String scene){
        try{
            return sceneConfig.get(scene).clone();
        }catch (Exception e){
            return null;
        }
    }
    @Override
    @RefreshScope
    public void setEnvironment(Environment environment) {
        initSceneConfig(environment);
    }

    private void initSceneConfig(Environment env) {
        log.info("scenesPrefixs:{}",scenesPrefixs);
        Binder binder = Binder.get(env); //绑定简单配置
        for (String scPrefix : scenesPrefixs.split(",")) {
            SceneProperties param=binder.bind("system." + scPrefix.toLowerCase(), Bindable.of(SceneProperties.class)).get();
            param.setBussinessId(scPrefix);
            sceneConfig.put(scPrefix,param);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值