1.在src/resource/application.properties文件中修改
2.在src/resource目录下创建application.yml文件
注意:数据前边必须有空格
3.在src/resource目录下创建application.yaml文件
分为.yml和.yaml两种文件扩展名
@Value("${lession}")
private String lession;
@Value("${enterprise.name}")
private String name;
@Value("${enterprise.age}")
private Integer age;
@Value("${enterprise.subject[0]}")
private String subject;
1.创建Environment对象,并使用spring对其自动装配实现将yml数据封装到environment对象中
2.通过environment.getProperties(“属性名”)来获取数据
@Autowired
private Environment environment;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id)
{
System.out.println("id为"+id);
System.out.println(environment.getProperty("lession"));
System.out.println(environment.getProperty("enterprise.name"));
System.out.println(environment.getProperty("enterprise.age"));
System.out.println(environment.getProperty("enterprise.subject[2]"));
return "Hello,SpringBoot!";
}
a.创建实体类Enterprise,添加注解@ConfigurationProperties(prefix = “enterprise”)来加载yaml配置文件
package com.itheima.domain;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
private String name;
private Integer age;
private String tel;
private String[] subject;
public Enterprise()
{
}
public Enterprise(String name, Integer age, String tel, String[] subject) {
this.name = name;
this.age = age;
this.tel = tel;
this.subject = subject;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String[] getSubject() {
return subject;
}
public void setSubject(String[] subject) {
this.subject = subject;
}
@Override
public String toString() {
return "Enterprise{" +
"name='" + name + '\'' +
", age=" + age +
", tel='" + tel + '\'' +
", subject=" + Arrays.toString(subject) +
'}';
}
}
b.在使用的时候创建实体类对象,再通过spring来实现自动注入
c.输出结果