1.修改服务器端口号
1.在src/resource/application.properties文件中修改
2.在src/resource目录下创建application.yml文件
注意:数据前边必须有空格
3.在src/resource目录下创建application.yaml文件
配置文件加载顺序
yml、yaml自动提示消失
yaml
yaml格式
分为.yml和.yaml两种文件扩展名
语法规则
yaml数据读取方式
1.使用@Value读取单个数据,属性名引用方式${一级属性名.二级属性名…}
@Value("${lession}")
private String lession;
@Value("${enterprise.name}")
private String name;
@Value("${enterprise.age}")
private Integer age;
@Value("${enterprise.subject[0]}")
private String subject;
2.封装全部数据到Environment对象
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!";
}
3.将数据封装到自定义实体类中
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.输出结果
多环境开发配置
多环境命令行启动参数设置