获取配置文件变量工具类

本文最后更新于:2 年前

Springboot中获取配置文件变量的工具类。

上天

YML配置文件

代码如下

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

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Properties;

/**
* @ClassName PropertiesUtil
* @Author by septzhang
* @Date 2022/7/25 18:20
* @Description 获取配置文件变量工具
* @Version 1.0
**/
public class PropertiesUtil {
//配置常量配置文件,默认路径是 /resources/*。yml
private static String PROPERTY_NAME = "application-common.yml";

/**
* 获取参数
* @param key String参数key值
* @return String Value
*/
public static Object getCommonYml(Object key){
Resource resource = new ClassPathResource(PROPERTY_NAME);
Properties properties = null;
try {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(resource);
properties = yamlFactory.getObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return properties.get(key);
}
}

Junit测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @ClassName PropertiesUtilTest
* @Author by septzhang
* @Date 2022/7/25 18:33
* @Description 测试工具类 PropertiesUtil
* @Version 1.0
**/
@SpringBootTest
public class PropertiesUtilTest {
@Test
public void testgetProperties(){
assertEquals(PropertiesUtil.getCommonYml("tg.token"),"********************");
assertEquals(PropertiesUtil.getCommonYml("tg.username"),"ajie1024_bot");


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!