SpringBoot默认两种格式的配置文件: application.properties和application.yml 。可以通过这两个配置文件来修改Spring Boot加载的自动配置。
1.YAML的特点
- 以数据为中心,因此适合用于配置文件
- 以键值对来描述数据:键:(空格)值
- 以空格来控制数据的层级关系
- 大小写敏感
2.YAML配置的写法
(1) 值为字面值,直接在值的位置配置属性值,默认为字符串,不需要添加双引号。
(2) 对象(map),语法示例:
user:
user-name: majunjie
age: 17
行内写法示例:
company: {address: 深圳, compName: company_name }
(3)数组或集合,语法示例:
score:
- 88
- 99
行内写法示例:
interests: [eat, sleep]
3. 使用 @ConfigurationProperties绑定YAML配置与对象属性
代码示例:
/**
* @ConfigurationProperties绑定批量的配置,支持松耦合,数据校验和 复杂对象
*/
@Validated // 开启数据校验机制 配合@ConfigurationProperties一起使用
@Component //使用@ConfigurationProperties的前提是当前对象必须是spring容器中的组件
@ConfigurationProperties(prefix = "user")
public class User {
@NotNull //数据检验
private String userName;
@Max(29) //数据检验
@Min(5)
private Integer age;
private Company company;
private String[] interests;
添加依赖,开启配置项自动提示功能
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
4. 使用@Value绑定配置项
示例代码(同时适用于.yml和.properties类型的文件):
@Value("${user.userName}") // 注意:类的属性名必须和配置文件中的完全一致
private String userName;
5. @ConfigurationProperties和@Value的对比
对比 | @ConfigurationProperties | @Value |
---|---|---|
功能 | 批量属性的绑定 | 单个属性的绑定 |
松耦合绑定 | 支持 | 不支持 |
SPEL表达式 | 不支持 | 支持 |
复杂对象 | 支持 | 不支持 |
JSR303数据校验 | 支持 | 不支持 |
6. 加载外部属性配置文件
一般情况下,以application命名的配置文件是专门用于修改SpringBoot自动加载的默认配置项的。如果需要对外部属性进行配置,则需要新建外部属性配置文件,需要注意的是:外部属性配置文件的类型必须是.properties类型*。
以userConfiguration.properties配置文件的使用为例:
#userConfiguration.properties中关于 user类的配置项
user.userName=majunjie
user.age=17
user.interests=[eat, sleep]
user.company.address=shenzhen
user.company.address.compName=companyName
@PropertySource("classpath:user.properties") //指定外部属性配置文件的存放路径
@Component //使用@ConfigurationProperties的前提是当前对象必须是spring容器中的组件
@ConfigurationProperties(prefix = "user")
public class User {
private String userName;
private Integer age;
private Company company;
private String[] interests;
7. SpringBoot加载Spring配置文件
SpringBoot默认使用配置类来代替applicationContext.xml,因此SpringBoot应用在启动时不会加载Spring的配置文件,如果需要加载,则需手动配置SpringBoot的启动类:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource("claspath:applicationContext.xml") //指定applicationContext.xml的存放路径
// spring boot默认推荐使用配置类而不是配置文件
//如果需要使用spring applicationContext.xml来进行bean的配置 则在此处使用该注解
@SpringBootApplication
public class SpringinitializrdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringinitializrdemoApplication.class, args);
}
}