1.@Value注释
@Value("${name}")
private String name;
@Value("${person.name}")
private String name2;
@RequestMapping("/hello2")
public String hello2(){
System.out.println(name);
return name+"||"+name2;
}
2.Enviroment
@Autowired
private Environment env;
@RequestMapping("/hello2")
public String hello2() {
System.out.println(env.getProperty("person.name"));
return name;
}
3.@ConfigurationProperties
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component //表示Person类被Spring识别为一个bean
@ConfigurationProperties(prefix = "person") //prefix前缀对应配置文件的对象名
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name=" + name +
", age=" + age +
'}';
}
public void setAge(int age) {
this.age = age;
}
}
Controller类
@Autowired
private Person person;
@RequestMapping("/hello2")
public String hello2() {
System.out.println(name);
System.out.println(env.getProperty("person.name"));
System.out.println(person);
return name + "||" + name2 + "||" + name3;
}
附配置文件
server:
port: 8082
name: abc
# 对象
person:
name: ${name}
age: 20
person2: {name: zhangsan,age: 20}
#数组
address:
- person
- shanghai
#数组行内
address2: {beijing,shanghai}
#纯量
msg1: 'hello \n world' #不会识别转义字符
msg: "hello world" #会识转义字符