application.properties文件
(1) 不适用于静态方法,需要@component或@RestController等注入到bean中
@Value("${log.path}")
(2)可用于静态方法
Properties p = PropertiesLoaderUtils.loadAllProperties("application.properties");
String path= p.getProperty("log.path");
application.yml配置文件
(1)同上@Value
(2) 不能用于静态方法
@Autowired
Environment env;
String path= env.getProperty("log.path");
(3)适用于相同前缀的分层属性。其中prefix =相同前缀属性
@Component
@ConfigurationProperties(prefix = "log")
public class LogConfig {
private String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
@Autowired
LogConfig logConfig;
String path = logConfig.getPath();
(4)适用于静态方法中使用
try {
Yaml yaml = new Yaml();
URL url = FileUtil.class.getClassLoader().getResource("application.yml");
if (url != null) {
//获取application.yml文件中的配置数据,然后转换为obj,
Object obj =yaml.load(new FileInputStream(url.getFile()));
//也可以将值转换为Map
//这里具体看你的配置文件有几层,我只有两层,所以两个Map套娃就够了
Map<String, Map<String, String>> map =(Map)yaml.load(new FileInputStream(url.getFile()));
//通过map我们取值就可以了.
Map<String, String> logmap = map.get("log");
serverURL = logmap.get("path");
}
} catch (IOException e) {
e.printStackTrace();
}