SpringBoot 配置参数化

SpringBoot配置文件优先级:yaml = yml > properties

常用的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
spring:
# 数据库配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/nodaoli
username: nodaoli
password: nodaoli
servlet:
# 文件上传配置
multipart:
# 单个文件最大上传大小
max-file-size: 10MB
# 多个文件最大上传大小
max-request-size: 100MB
mybatis:
configuration:
# 设置Mybatis的日志功能
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 启用Mybatis的自动驼峰大写功能
map-underscore-to-camel-case: true

说明

application.properties文件中配置参数,前面的accessKeyId是自己随便写的,后面是实际配置的参数

1
2
3
4
r2.accessKeyId=xxxx
r2.secretAccessKey=xxxxxxxxxxxx
r2.endpoint=https://xxxxxxxxxx.r2.cloudflarestorage.com
r2.bucketName=xxxx

使用@Value("${r2.accessKeyId}")来获取配置参数

1
2
3
4
public class R2Config {
@Value("${r2.accessKeyId}")
private String accessKeyId;
}

推荐使用yml/yaml文件来配置参数,因为层级比较明确,而且优先级高于properties文件

1
2
3
4
5
6
7
8
9
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
r2:
accessKeyId: xxxx
secretAccessKey: xxxxxxxxxxxxx
endpoint: https://xxxxxxxxxx.r2.cloudflarestorage.com
bucketName: xxxx

使用@ConfigurationProperties自动绑定

  1. 先使用@Data 注解来生成getter/setter方法
  2. 在使用@component 注解来将这个类注册为Spring Bean,被Spring管理
  3. 使用@ConfigurationProperties注解来绑定配置参数,prefix属性指定配置参数的前缀
1
2
3
4
5
6
@Data
@Component
@ConfigurationProperties(prefix = "r2")
public class R2Config {
private String accessKeyId;
}

然后在需要使用的类中使用@Autowired注解来注入这个R2Config类,并且使用get/set方法来获取配置参数