@[TOC]
1 yml示例
name: 胡思源
# 对象
person:
name: ${
name}
age: 1
# 数组
aoteman: [迪迦,赛罗]
guaishou:
- 亚波人
- 贝利亚
# 纯量
msg1: 'hello \n world' # 不会识别转义符,会原样输出
msg2: "hello \n world" # 会识别转义字符
2 @Value
@Value("${name}")
private String name;
@Value("${person.age}")
private String age;
@Value("${aoteman[0]}")
private String atm;
3 Environment
@Autowired
private Environment env;
public void test(){
System.out.println(env.getProperty("person.name"));
System.out.println(env.getProperty("aoteman[0]"));
}
4 @ConfigurationProperties
- 写配置文件对应的实体类
```java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
private String[] address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
* 读取配置文件并使用
```java
@Autowired
private Person person;
public void test(){
System.out.println(person);
System.out.println(person.getAddress()[0]);
System.out.println(person.getAddress()[1]);
}