本文共 2739 字,大约阅读时间需要 9 分钟。
Spring Boot使用一个全局的配置文件,文件名为固定的application.properties或application.yml。配置文件的作用是修改Spring Boot自动配置的默认值,Spring Boot会自动为我们配置好很多参数。
YAML( Yet Another MarkDown Language)是一种标记语言,广泛用于配置文件中。YAML的特点是以数据为中心,适合存储配置信息。
key: value,键和值之间必须有空格。":不会转义特殊字符。' ':会转义特殊字符。key: value,下一行继续写对象属性。-表示数组中的元素。server: port: 8088
server: port: 8888
8081
@Component@ConfigurationProperties(prefix = "person")public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map maps; private List server: port: 8081person: age: 12 boss: true last-name: zlj birth: 2022/12/17 maps: k2: v2 k1: v1 lists: - zlj - zzg dog: name: z age: 13
@Component@PropertySource(value = {"classpath:person.properties"})@ConfigurationProperties(prefix = "person")public class Person { // ...} ${random.value}:随机值${random.int}:随机整数${random.long}:随机长整数${random.int(10)}:生成长度为10的随机整数${random.int[1024,65536]}:在1024到65536之间生成随机整数person: age: 12 boss: true last-name: zlj birth: 2022/12/17 maps: k2: ${random.int} k1: ${random.int} lists: - zlj - zzg dog: name: zl age: 13 person.last-name=张三${random.uuid}person.age=${random.int}person.birth=2017/12/15person.boss=falseperson.maps.k1=v1person.maps.k2=14 spring: profiles: active: dev http: encoding: default: UTF-8
spring.profiles.active=devjava -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev-Dspring.profiles.active=devSpring Boot会从以下位置加载application.properties或application.yml:
file:./config/file:./classpath:/config/classpath:/java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties
Spring Boot会自动加载大量自动配置类,主要功能包括:
我们只需要关注Spring Boot默认配置中没有覆盖的部分,并通过配置文件修改需要自定义的参数。
转载地址:http://peqq.baihongyu.com/