1. 配置文件格式
提供三种属性配置方式,当三个配置文件都有,加载顺序从前至后
示例第二种(主要也是用这个):
2. yaml格式
3. yaml读取数据格式的三种方式
第一种,使用@Value读取单一属性数据
@Value("${lesson}")
private String lesson;
@Value("${server.port}")
private Integer port;
@Value("${enterprise.subject[0]}")
private String subject_00;
第二种,使用Environment封装全配置数据
//使用Environment封装全配置数据
@Autowired
private Environment environment;System.out.println(environment.getProperty("lesson"));
System.out.println(environment.getProperty("server.port"));
System.out.println(environment.getProperty("enterprise.age"));
System.out.println(environment.getProperty("enterprise.subject[1]"));
第三种,创建一个实体类enterprise
//封装yaml对象格式数据必须先声明当前实体类受Spring管控
@Component
//使用@ConfigurationProperties注解定义当前实体类读取配置属性信息,通过prefix属性设置读取哪个数据
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {private String name;private Integer age;private String tel;private String[] subject;@Overridepublic String toString() {return "Enterprise{" +"name='" + name + '\'' +", age=" + age +", tel='" + tel + '\'' +", subject=" + Arrays.toString(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;}
}
@Autowired
private Enterprise enterprise;System.out.println(enterprise);
4. 多环境开发配置
方便在生产环境、开发环境和测试环境切换环境;
选择yml配置方式;
#设置启用的环境
spring:profiles:active: dev---
#开发
spring:config:activate:on-profile: dev
server:port: 80
---
#生产
spring:config:activate:on-profile: pro
server:port: 81
---
#测试
spring:config:activate:on-profile: test
server:port: 82
---
5. 多环境启动命令格式
将项目打包之后的jar包发给其他人员时(测试),启动命令格式;
命令行中动boot程序;
此时80端口改成了82端口
当测试端需要修改端口号(例如:测试端的端口号有冲突);
只需要在命令行中执行;
6. 多环境开发兼容问题
Maven与boot配置多环境配置时,Maven中配置的profile起主导作用;