一、代码展示
1、新建Person类,代码如下:
package com.lc.springboot_testbilbil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
@Component
@ConfigurationProperties
public class Person {
private String name;//name和age要与yml里的一致!
private int age;
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2、Controller类代码如下:
package com.lc.springboot_testbilbil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${name}")
private String Name;
@Value("${person1.name}")
private String Name1;
@Autowired
private Environment env;
@Autowired
private Person person3;
@RequestMapping("/helloYML")
public String hello(){
System.out.println(Name);
System.out.println(Name1);
System.out.println("person2.name是"+env.getProperty("person2.name"));
System.out.println("person2.age是"+env.getProperty("person2.age"));
System.out.println("person1.name是"+env.getProperty("person1.name"));
System.out.println("person1.age是"+env.getProperty("person1.age"));
System.out.println("-----------------------------");
System.out.println(person3);
return "Hello World! 你好林月明!";
}
}
3、Application类代码如下:
package com.lc.springboot_testbilbil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootTestBilBilApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTestBilBilApplication.class, args);
}
}
4、.yml文件中代码如下:
server:
port: 8081
name : XiaoLi
#对象
person1:
name : ${name}
#XiaoLi
age : 20
#对象行内写法
person2 : {name: XiaoYue, age: 30}
#数组
address1 :
-Nanning
-Liuzhou
#数组行内写法
address2 : [Nanning,Liuzhou]
#纯量
msg1 : 'hello \n world'
#不会识别转义字符,导致原样输出
msg2 : "hello \n world"
#会识别转义字符
5、参考链接2,注意该文件中至少存在一对花括号,否则可能会报错Error:java: Invalid additional meta-data in 'META-INF/spring-configuration-metadata.json': End of in...
{
}
6、后台运行结果:
二、若Person类中@ConfigurationProperties带有前缀prefix
@ConfigurationProperties(prefix = "person2")
1、运行结果
2、原因解释
带有前缀prefix= "person3",才会得到对应person3配置中的值。若无前缀,int默认值为0。
name : XiaoLi
#对象
person1:
name : ${name}
#XiaoLi
age : 20
#对象行内写法
person2 : {name: XiaoYue, age: 30}
三、参考教程
1、黑马程序员SpringBoot基础教程https://www.bilibili.com/video/BV1Lq4y1J77x?p=11&vd_source=841fee104972680a6cac4dbdbf144b50
2、resources报错解决https://blog.csdn.net/niuzaiwenjie/article/details/80882934