读取系统环境变量配置

前言

公司的配置文件放在系统环境变量指定的位置,下边记录如何获取配置文件

实现1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import com.easyliao.jwt.conf.Conf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
* 加载指定路径系统环境变量
*/

public class ConfigLoader {

private static ConfigLoader instance = null;
private Properties globalConfigs = null;

public static ConfigLoader getInstance() {
if (instance == null) {
instance = new ConfigLoader();
}
return instance;
}

private ConfigLoader() {
this.init();
}

private void init() {
boolean hasConfig = this.checkHasConfig(System.getenv(Conf.SYS_ENV));
if (!hasConfig) {
throw new RuntimeException("没找到全局配置文件");
}
}

private boolean checkHasConfig(String baseEnv) {
String defaultPath = baseEnv + File.separator + "conf" + File.separator;
File file = new File(defaultPath);
if (file.exists() && file.isDirectory()) {
File conf = new File(defaultPath + Conf.DEFAULT_CONF_NAME);
if (conf.exists() && conf.isFile()) {
this.globalConfigs = new Properties();
try {
FileInputStream inputStream = new FileInputStream(conf);
this.globalConfigs.load(inputStream);
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
} else {
return false;
}
}

public String getProperty(String key) {
return this.globalConfigs.getProperty(key, null);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Conf {

/**
* 系统环境变量key
*/
public static final String SYS_ENV = "IDEA360_HOME";

/**
* 默认配置文件名
*/
public static final String DEFAULT_CONF_NAME = "conf.properties";
}

实现2

1
2
3
4
5
6
7
8
public class NlpKbProxyApplication {

public static void main(String[] args) {
SysConfig.configure();
SpringApplication.run(NlpKbProxyApplication.class, args);
}

}

将外部配置文件中的变量注入系统变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Component
public class SysConfig {

private static final String EASYLIAO_HOME = "EASYLIAO_HOME";
private static final String FOLDER = "conf";
private static final String CONFIG_NAME = "conf.properties";

public static String NLP_SERVERS;

public static void configure() {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(new File(System.getenv(EASYLIAO_HOME) + File.separator + FOLDER + File.separator + CONFIG_NAME)));
System.getProperties().putAll(properties);
NLP_SERVERS = properties.getProperty("nlp.bootstrap.servers");
} catch (IOException e) {
e.printStackTrace();
}
}
}

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。