一.默认配置文件:application.properties文件
//application.properties文件
student.name=lisi
student.age=18
二.Bean属性与配置文件绑定:通过注解的方式
1.@Value
@Component//必须是一个Bean 名称精确匹配
public class Student {
@Value("${student.name}")
private String name;
@Value("${student.age}")
private Integer age;
}
2.@ConfigurationProperties
@Component//必须是一个Bean 名称模糊匹配
@Data//需要setter设值
@ConfigurationProperties("student")//以student开头的配置项
public class Student {
private String name;
private Integer age;
}
3.@EnableConfigurationProperties
//Student.java
// 读取以student开头的配置项,不加@Componnet
@ConfigurationProperties("student")
@Setter
public class Student {
private String name;
private Integer age;
}
//Config.java
// 统一加载到ioc
@Configuration
@EnableConfigurationProperties({Student.class})//用于一次加载多个 和 注解无法扫描的情况
public class Config {
}
三.YAML配置文件
1.application.yml替换原有的application.properties文件
原因:解决难以阅读,层次结构不清晰的问题
//application.yml文件
student:
name: 李四
age: 18
可以使用SPEL表达式引用别的值:${}
四.多环境配置文件
1.主要分为开发/测试/生产(上线) 环境
2.如果多个环境使用同一个配置文件,这个配置文件必须经常修改
3.多环境配置文件就是一个环境对应一个配置文件,不同环境生效不同配置
步骤:
1.添加各个环境的配置
//application.yml
//主配置文件(无论如何都会加载)
//用于配置与环境无关的信息(如spring应用名)
spring:
application:
name: SpringBoot
profiles:
active: dev #激活dev环境
//application-dev.yml
student:
name: 李四
age: 18
2.激活环境
(1)通过配置文件指定:在application.yml中添加spring.profiles.active: dev(激活开发环境)
(2)通过程序实参:--spring.profiles.active=test(激活测试环境)优先级最高
注意事项:
1.spring.profiles.active必须写在主配置文件里
2.最终生效配置= 主环境配置+ 激活环境配置,如果配置冲突激活环境配置优先
3.spring.profiles.active: 配置名,必须和application-配置名.yml匹配,否则只有主配置生效
配置文件位置:
优先级:程序实参> 项目外部config > 项目外部> resources/config > resources