springboot配置文件
配置文件文档
默认配置文档:Common Application properties
1、配置文件名
SpringBoot的配置文件的名称是固定的:
application.yml application.properties
2、配置文件的作用
SpringBoot的配置文件与SpringMVC的配置文件作用是一样的,用于管理配置项,程序运行时,将配置项读取到程序中。但区别是SpringBoot自动配置了默认值,当没有什么特殊要求时,可以直接采用默认值,相当于简化了配置操作,所以才有开箱即用的说法。
3、yml与properties的配置写法
yml文件
通过空格来确定层级关系;只要是左对齐的一列数据,都是同一个层级的;属性和值也是大小写敏感;
server: port: 8080
properties:
server.port = 8081
4、常见的配置项
端口号及访问路径
server.port=8081 server.servlet.context-path=/MySpringboot
##http://localhost:8081/MySpringboot
随机端口(未测试)
#随机8081到9999的中的某一个端口 server.port=${random.int[8081,9999]}
多配置文件切换
在主配置文件(application.properties)中引入其他的配置文件(application-db.properties);可以用于切换不同的配置文件,用于分离开发配置与部署配置
spring.profiles.active = db
自定义属性配置
在代码中使用@Value注解,可以获取配置文件中的自定义属性配置 ;在代码中的属性字段上添加@Vaule注解,一般放在实现类中;
@Value不支持注入静态变量,可间接通过Setter注入来实现。
temp-path = D:/path/files common.file.path = D:/path/files
java代码
@Value("${temp-path}") private String filePath;
##静态变量赋值
private static String filePath;
@Value("${temp-path}")
public String setFilePath(String filePath){
this.filePath = filePath;
}
数据源配置
##基于springboot版本的不同,写法稍微有点不一样,但大致就是这种形式 spring.datasource.url= spring.datasource.username= spring.datasource.password= spring.datasource.driver-class-name=org.postgresql.Driver
对象、Map(属性和值)(键值对):
使用@ConfigurationProperties 读取多个属性,可以将配置项读取到bean中;也可以使用@Vaule在每个属性上赋值
asr.client.bufferSize=3200 asr.client.mindB=10 asr.client.minSection=1 asr.client.sectionGap=10
@Component @ConfigurationProperties(prefix = "asr.client") public class MyAsr{ private int bufferSize;
private int mindB;
private int minSection;
private int sectionGap;
// 提供Setter 和 Getter 方法
}
需要引入配置文件处理依赖
<!--导入配置文件处理器,配置文件进行绑定就会有提示--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
List、set,数组等
numbers=105,106,107,108
##也可以
code.numbers[0]=102
code.numbers[1]=103
code.numbers[2]=104
code.numbers[3]=105
使用@Value解析需要人工处理,@ConfigurationProperties则会自动解析
@Value("#{'${numbers}'.split(',')}") private List<Integer> numbers;
yml文件中的写法
lists: - hahaha - heiheihei ##行内写法 lists: [hahaha,heiheihei]
Map的写法
java中使用@ConfigurationProperties解析,也可以使用@Value获取
#map 第一种方式 data.numMap.first=1 data.numMap.second=2 data.numMap.third=3 data.numMap.fourth=4 #map 第二种方式 data.numMap[first]=1 data.numMap[second]=2 data.numMap[third]=3 data.numMap[fourth]=4
yml文件中的写法
##行内写法 numMap: {first: 1,second: 2,third: 3,fourth: 4} ##跨行写法 numMap: first: 1 second: 2 third: 3 fourth: 4
配置文件占位符${....}
${uuid}、${url}、${username} #适用于多配置文件时使用,在主文件中使用占位符, #在引入的配置文件中声明占位符的值
配置文件加载位置
SpringBoot 会在下列指定的路径下查找默认的配置文件application.yml(application.properties),按优先级从高到低进行排列:
工程根目录的config目录:file:./config/
工程根目录:file:./
类路径的config目录:classpath:/config/
类路径:classpath:/
(推荐使用)
如果存在多个配置文件,则严格按照优先级进行覆盖,使用最高优先级的配置文件(建议配置文件只创建一个,可以采用引入外部文件的形式来实现切换配置的问题)