在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);
}
}
}