SpringBoot提供了2种配置文件类型:properties和yml/yaml
默认配置文件名称:application
在同一级目录下优先级为:properties>yml>yaml
yml:基本语法
大小写敏感
数据值前边必须又空格,作为分隔符
使用缩进表示层级关系
缩进时不能使用Tab键,只能使用空格
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
#表示注释,从这个字符一直到行尾,都会被解析器忽略
yml:数据格式:
对象(map): 键值对的集合
数组: 一组按次序排列的值
address:
- beijing
-shanghai
纯量:
单引号不会识别转义字符
双引号会是被转义字符
参数引用
${key}
读取配置内容
@Value
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${person.name}")
private String name;
@RequestMapping("/hello")
public String hello(){
return name;
}
}
Environment
package com.gc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${person.name}")
private String name;
@Autowired
private Environment env;
@RequestMapping("/hello2")
public String hello2(){
return env.getProperty("person.name");
}
@ConfigurationProperties
package com.gc.pojo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component//表示可以被spring识别
@ConfigurationProperties(prefix = "person")//prefix指定配置文件中的变量名
public class Person {
private String name;
}
package com.gc.controller;
import com.gc.pojo.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${person.name}")
private String name;
@Autowired
private Environment env;
@Autowired
private Person person;
@RequestMapping("/hello3")
public String hello3(){
return person.getName();
}
解决如下问题的方法:添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
profile
profile功能就是来进行动态配置切换的
profile配置方式:
多文件方式:
spring.profiles.active=dev //需要用哪一个文件
yml多文档方式
#application.yml文件
---
server:
port: 8081
spring:
profiles: dev
---
server:
port: 8082
spring:
profiles: pro
---
server:
port: 8083
spring:
profiles: test
---
spring:
profiles:
active: pro
profile激活方式:
配置文件:在配置文件中配置:spring.profile.activedev
虚拟机参数:在VM options指定: -Dspring.profiles.active=dev
命令行参数:java-jar xxx.jar --spring.profiles.active=dev
内部配置加载顺序
SpringBoot程序启动时,会从以下位置加载配置文件:
1.file.../config/ : 当前项目下的/config目录下
2.file.../ :当前项目的根目录
3.calsspath:/config/: classpath的/config目录
4.calsspath:/ : classpath的根目录
加载顺序为上述的排列顺序,高优先级配置的属性会生效
外部配置加载顺序
详情见官网