本文在 Spring Boot 2.3.1.RELEASE 下测试通过,请注意版本,也许并不适合将来的版本。

正确的姿势

POJO

1
2
3
4
5
6
7
8
9
10
11
12
@Data
@Configuration
@PropertySource("classpath:config-biz.properties")
@ConfigurationProperties(prefix ="config")
public class ConfigBiz {
private String env;
private String logDirectoryPath;
private String isSendEmailWhenException;
private String mailFrom;
private String whenExceptionMailTo;
private String batchUpdateRecordsLimit;
}

配置文件

1
2
3
4
5
6
7
8
9
config.logDirectoryPath=C:/logs
config.env=local
config.isSendEmailWhenException=N
config.isSetResJsonForApiCallLogWhenSuccess=N
config.mailFrom=1614923608@qq.com
config.whenExceptionMailTo=552087293@qq.com

# 系统通用配置:批量修改,限制记录数
config.batchUpdateRecordsLimit=500

备忘

  • 早期版本 Spring Boot 1.5.X 也可以用这种方式配置。
  • POJO 文件中的 @Configuration 可换成 @Component。
  • 不可读取 yml 格式的文件,只能读取 properties 后缀的文件。
  • 需要配合 @ConfigurationProperties 注解。
    • 不指定前缀,直接是 @ConfigurationProperties,程序可正常运行,但 IDEA 会报红色波浪线,可以不理会,不过,对于有代码洁癖的人来说,这是不可接受的,见下图:
    • 如果看着红色波浪线不爽,那就添加一个前缀吧,如:@ConfigurationProperties(prefix ="config"),这样还可以把不同的配置信息放到一个 .properties 文件里,不同的 POJO 通过前缀来获取自己的属性字段。

踩过的坑

之前的项目采用 Spring Boot 2.1.6.RELEASE,通过以下注解:

1
2
3
@Data
@Configuration
@PropertySource("classpath:config-biz.properties")

再配合属性注解 @Value("${属性字段名}"),即可完成配置的初始化,如下:

1
2
3
4
5
6
7
8
9
10
11
12
@Data
@Configuration
@PropertySource("classpath:config-biz.properties")
public class ConfigBiz {
@Value("${env}")
private String env;

@Value("${logDirectoryPath}")
private String logDirectoryPath;

// ...
}

最近的项目,用了当前最新的 Spring Boot 2.3.1.RELEASE,这种方式已经不行了,程序编译没问题,发生运行时错误,提示:

1
2
3
4
5
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'env' in value "${env}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer$PlaceholderResolvingStringValueResolver.resolveStringValue(PropertyPlaceholderConfigurer.java:230) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
...

  • 网上的文章,针对以上错误信息,原因各异,使用的 Spring Boot 版本也是五花八门,针对较新的版本的文章比较少。建议直接查官网文档。
  • 另外,Spring Boot 2.2.2.RELEASE,这个版本已经不支持了。

查看或下载 Spring Boot 官网文档

该网址可选择三种不同的文档方式查看:https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/

如果想查看其它版本的文档,把链接中的版本号替换成你想要查看的。

三种类型文档

  1. html/:就是 Spring Boot 官网 https://spring.io/projects/spring-boot#learn 页面各个版本后面的 Reference Doc 链接地址,带大主题目录,方便选择性的阅读。
  2. htmlsingle/:如果想要在线搜索内容,就这个链接了,Ctrl + F,你懂的,比如,本文遇到的问题,直接搜索 @PropertySource。左边也有章节目录。
  3. pdf/:可以下载到本地慢慢查看,搜索也比较方便。