获取配置文件变量工具类
本文最后更新于: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;
public class PropertiesUtil { private static String PROPERTY_NAME = "application-common.yml";
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测试
|
@SpringBootTest public class PropertiesUtilTest { @Test public void testgetProperties(){ assertEquals(PropertiesUtil.getCommonYml("tg.token"),"********************"); assertEquals(PropertiesUtil.getCommonYml("tg.username"),"ajie1024_bot");
|