import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.util.Properties;
/**
* 用户获取配置文件中属性值 不依赖于spring
*
* @author cjj
* @date 2019/8/4
*/
public class PropertiesUtils {
private static String yml;
//静态代码块,自动获取用户配置的配置文件
static {
yml = (String) getYml("spring.profiles.active");
if (yml != null && !"".equals(yml)) {
yml = "-" + yml;
} else {
yml = "";
}
}
/**
* 根据传入的yml获取yml中key的属性值
*
* @param key
* @param yml
* @return
*/
public static Object getYml(Object key, String yml) {
Resource resource = new ClassPathResource(yml);
Properties properties;
try {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(resource);
properties = yamlFactory.getObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return properties.get(key);
}
/**
* 自动根据 application中激活的配置文件,选择对应的yml读取属性
*
* @param key
* @return
*/
public static Object getYml(Object key) {
Object value = getYml(key, "application.yml");
if (value != null) {
return value;
}
if (!yml.contains("application")) {
yml = "application" + yml + ".yml";
}
return getYml(key, yml);
}
public static void main(String[] args) {
System.out.println(getYml("server.port"));
}
}
SpringBoot 不依赖Spring读取任意yml配置
最新推荐文章于 2024-08-28 09:20:15 发布