SpringBoot获取获取yml和和properties配置文件的内容配置文件的内容
主要为大家详细介绍了SpringBoot获取yml和properties配置文件的内容,具有一定的参考价值,感兴趣的小伙
伴们可以参考一下
(一)(一)yml配置文件:配置文件:
pom.xml加入依赖:
<!-- 支持 @ConfigurationProperties 注解 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
</dependency>
在application.yml文件中加上:
#自定义的属性和值
myYml:
simpleProp: simplePropValue
arrayProps: 1,2,3,4,5
listProp1:
- name: abc
value: abcValue
- name: efg
value: efgValue
listProp2:
- config2Value1
- config2Vavlue2
mapProps:
key1: value1
key2: value2
使用一个java类获取yml文件的内容:
package com.sun.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 加载yaml配置文件的方法
* Created by sun on 2017-1-15.
* spring-boot更新到1.5.2版本后locations属性无法使用
* @PropertySource注解只可以加载proprties文件,无法加载yaml文件
* 故现在把数据放到application.yml文件中,spring-boot启动时会加载
*/
@Component
//@ConfigurationProperties(locations = {"classpath:config/myProps.yml"},prefix = "myProps")
@ConfigurationProperties(prefix = "myYml")
public class YmlConfig {
String simpleProp;
private String[] arrayProps;
private List<Map<String, String>> listProp1 = new ArrayList<>(); //接收prop1里面的属性值
private List<String> listProp2 = new ArrayList<>(); //接收prop2里面的属性值
private Map<String, String> mapProps = new HashMap<>(); //接收prop1里面的属性值
public String getSimpleProp() {
return simpleProp;
}
//String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要
public void setSimpleProp(String simpleProp) {
this.simpleProp = simpleProp;
}
public String[] getArrayProps() {
return arrayProps;
}