SpringBoot自定义配置文件读取

有时候我们把配置都放到application.yml文件里面会造成此文件相当不好管理,所以我们可以有意识的进行拆分,将一些配置放到其他的配置文件里面,那么我们如何加载并使用它呢,其实很简单,直接读取然后放到Properties对象中就OK了,看代码

读取配置

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
package com.pibgstar.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
* @author pibigstar
* @desc 加载配置文件
**/
public class ConfigUtil {
private static Logger logger = LoggerFactory.getLogger(ConfigUtil.class);
// 配置文件的路径
private static final String CONFIG_NAME = "conf/config.properties";
private static Properties ps;

public static int getInt(String key) {
String value = getValue(key);
return Integer.parseInt(value);
}

public static String getString(String key) {
String value = getValue(key);
try {
return new String(value.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}

private static String getValue(String key) {
if (ps == null) {
init();
}
String value = null;
if (StringUtils.isEmpty(value)) {
value = ps.getProperty(key);
}
logger.info("key:"+key+"----value:"+value);
return value;
}

private static synchronized void init() {
try {
InputStream ras = ConfigUtil.class.getClassLoader().getResourceAsStream(CONFIG_NAME);
ps = new Properties();
ps.load(ras);
} catch (IOException e) {
e.printStackTrace();
}
}

}

配置文件放置

我们将config.properties放到resources下新建的conf文件夹下面就OK了

1
2
pibigstar.demo.url=http://www.pibigstar.com
pibigstar.demo.number=8

使用

1
2
3
4
5
6
7
public class TestConfigUtil {
public static void main(String[] args){
String url = ConfigUtil.getString("pibigstar.demo.url");
int number = ConfigUtil.getInt("pibigstar.demo.number");
System.out.println(url + " " + number);
}
}
-------------本文结束感谢您的阅读-------------