springboot 默认使用 application.yaml 文件来进行全局配置的,主要目的就是修改 springboot 自动配置的默认值。
1、yaml 核心语法汇总
以 空格 的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的,且属性和值都是大小写敏感的。
server: port: 8081 path: /hello
2、值的写法
2.1、字符串默认不用加上单引号或者双引号;
“”:双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思
name: “zhangsan lisi”:输出;zhangsan 换行 lisi
‘’:单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据
name: ‘zhangsan
lisi’:输出;zhangsan
lisi
2.2、map 写法
friends: lastName: zhangsan age: 20
也可以使用行内写法
friends: {lastName: zhangsan,age: 18}
3、配置文件值注入
配置文件 application.yml
person: lastName: hello age: 20 boss: true birth: 2018/03/18 maps: {k1: v1,k2: 12} lists: - hfbin - zhaoliu dog: name: dog age: 12
javaBean:
/** * 将配置文件中配置的每一个属性的值,映射到这个组件中 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定; * prefix = "person":配置文件中哪个下面的所有属性进行一一映射 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能; */ @Component @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog;
4、配置文件注入值数据校验
@Validated
@Component @ConfigurationProperties(prefix = "person") @Validated public class Person { private String lastName; private Integer age; private Boolean boss; }
5、加载指定配置文件
@PropertySource:加载指定的配置文件 --> person.properties
person.last-name=hfbin person.age=23 person.boss=true
@PropertySource(value = {"classpath:person.properties"}) @Component @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boss; }
6、配置文件占位符
6.1、随机数
${random.value}、${random.int}、${random.long} ${random.int(10)}、${random.int[1024,65536]}
6.2、占位符获取之前配置的值,如果没有可以是用:指定默认值
可以在配置文件中引用前面配置过的属性(优先级前面配置过的这里都能用)
person.last-name=张三${random.uuid} person.name=$person.last-name} person.age=${random.int} person.birth=2017/12/15 person.boss=false person.maps.k1=v1 person.maps.k2=14 person.lists=a,b,c person.dog.name=${person.hello:hello}_dog person.dog.age=15
${person.hello:默认值} 来指定找不到属性时的默认值
7、Profile 多环境
Profile是Spring对不同环境提供不同配置功能的支持,可以通过激活、 指定参数等方式快速切换环境 。
我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml
比如开发环境:application-dev.properties
生产环境 :application-prod.properties
默认使用application.properties的配置;
激活指定 profile
1、在配置文件application.properties中指定 spring.profiles.active=dev
2、命令行:
java -jar search-bs.jar --spring.profiles.active=dev;
可以直接在测试的时候,配置传入命令行参数
3、虚拟机参数;
-Dspring.profiles.active=dev
8、配置文件指定路径加载
项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置 ,并指定运行环境。例如:
java -jar search-bs.jar --spring.config.location=/data/config/application.yml --spring.profiles.active=dev