首页 > 其他 > 详细

从内外配置文件中读取配置信息

时间:2020-04-03 17:19:18      阅读:57      评论:0      收藏:0      [点我收藏+]

 

在项目中总会留一些配置项让用户根据需求修改,这时候就需要一个外部配置文件,同时我们可以在项目中放置一个默认配置文件。主要是通过继承spring提供的PropertyPlaceholderConfigurer这个类来实现的。具体的加载过程请参考如下代码

 

@Component
@Conditional(XXXCondition.class)  //根据条件选择是否加载这个component
public class EmbeddedPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private String outterProp;
String innerProp="xxxx.properties";
Properties configProps;

@Override
protected void loadProperties(Properties props) throws IOException {
if (configProps == null) {
init();
}
props.putAll(configProps);
}


private void init() {
InputStream innerStream=this.getClass().getClassLoader().getResourceAsStream(innerProp);
String content = readContent(innerStream);
addContent(content);

outterProp=System.getenv("resource_path");
if(outterProp==null){
logger.error("The path to the properties file, \"resource_path\", is not specified");
return;
}
Path outterPath = Paths.get(outterProp);
try (InputStream outterStream= Files.newInputStream(outterPath)){
content = readContent(outterStream);
addContent(content);
} catch (IOException e) {
logger.error(e.getMessage());
}
}

private void addContent(String content){

if (content == null || content.length() <= 0) {
return;
}

String[] ss = content.split("\n");
for(String s : ss) {
if (s == null || s.length() <= 0) {
continue;
}
String[] split = s.split("=",2);
String key = split[0];
if (key != null) {
key = key.trim();
}

if (key == null || key.length() <= 0 || key.charAt(0) == ‘#‘) {
continue;
}

String value = split[1];
if (value != null) {
value = value.trim();
}

if (this.configProps == null) {
this.configProps = new Properties();
}

this.configProps.put(key, value);
}
}

public static String readContent(InputStream inputStream) {

String encoding = "UTF-8";
StringBuffer buffer = new StringBuffer("");
try {
InputStreamReader read = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
buffer.append(lineTxt).append("\n");
}
read.close();

} catch (Throwable t) {
logger.error("error when read content", t);
}

return buffer.toString();
}

 

从内外配置文件中读取配置信息

原文:https://www.cnblogs.com/ZhengQiZHou/p/12627619.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!