如何在Spring的application.properties中定义并读取对象数组配置
问题解决方案
@Value注解仅支持注入基础类型、字符串、基础类型集合这类简单配置,不支持直接绑定自定义对象集合,需要配合@ConfigurationProperties实现,具体操作如下:
1. 调整配置类与对应实体
首先TokenStore.Token类需要提供无参构造方法,以及name、value、enabled三个字段对应的getter、setter方法。
配置类需要给tokenList添加getter、setter,修正后的代码如下:
@ConfigurationProperties("authorised") @Configuration public class AppTokenConfiguration { // 必须提供getter和setter,否则配置无法自动绑定 private List<TokenStore.Token> tokenList = new ArrayList<>(); @Bean public TokenStore getTokenStore() { // 若需要以value为Map的key,可将getToken替换为getValue return new TokenStore(tokenList.stream().collect(Collectors.toMap(TokenStore.Token::getName, Function.identity()))); } public List<TokenStore.Token> getTokenList() { return tokenList; } public void setTokenList(List<TokenStore.Token> tokenList) { this.tokenList = tokenList; } }
2. application.properties配置写法
按照Spring Boot的宽松绑定规则,列表类型的自定义对象配置写法如下,对应你给出的两个令牌示例:
# 第1个令牌配置 authorised.token-list[0].value=123456 authorised.token-list[0].name=specialToken authorised.token-list[0].enabled=true # 第2个令牌配置 authorised.token-list[1].value=56173 authorised.token-list[1].name=newToken authorised.token-list[1].enabled=false
3. 可选:application.yml配置写法
如果使用yml格式的配置文件,写法更贴合你给出的示例格式,可读性更高:
authorised: token-list: - value: 123456 name: specialToken enabled: true - value: 56173 name: newToken enabled: false
注意事项
- 如果启动时提示配置绑定失败,可在项目启动类上添加
@EnableConfigurationProperties(AppTokenConfiguration.class)注解,主动开启配置属性绑定功能 - 可引入
spring-boot-configuration-processor依赖,实现配置编写时的自动提示功能,非必须
内容的提问来源于stack exchange,提问作者tensor
相关产品推荐
相关产品推荐

