You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring中从properties文件注入String数组类型的List集合

配置与注入List<String[]>类型属性的实现方案

方案1:直接使用@Value+SpEL表达式实现

首先在application.properties中定义配置值,使用两种不同的分隔符区分外层列表和内层数组的元素:

# 分号分隔外层List的每个元素(即每个String数组),逗号分隔单个数组内的元素
LIST_OF_NESTED_ARRAYS=张三,男,25;李四,女,23;王五,男,27

然后修改原@Value注解,通过SpEL表达式完成两层拆分,直接得到List<String[]>类型:

@Value("#{'${LIST_OF_NESTED_ARRAYS}'.split(';').!{#this.split(',')}}")
List<String[]> list;

说明:上述SpEL表达式的逻辑为先按分号拆分得到每个数组的拼接字符串,再对每个字符串按逗号拆分得到String数组,最终自动封装为List集合。如果你的业务数据中包含逗号/分号,可以自行替换为其他不会出现在业务值中的分隔符,特殊字符需要加\转义。

方案2:使用@ConfigurationProperties更优雅实现(推荐)

如果不想写复杂的SpEL,用SpringBoot的配置绑定能力实现更易维护:

  1. 首先定义配置绑定类
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;

@ConfigurationProperties(prefix = "custom.config")
public class NestedArrayConfig {
    private List<String[]> nestedArrays;
    // 必须添加getter、setter方法
    public List<String[]> getNestedArrays() {
        return nestedArrays;
    }
    public void setNestedArrays(List<String[]> nestedArrays) {
        this.nestedArrays = nestedArrays;
    }
}
  1. 在启动类/配置类上开启配置绑定扫描
@SpringBootApplication
@EnableConfigurationProperties(NestedArrayConfig.class)
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  1. 在application.properties中按索引配置
custom.config.nested-arrays[0]=张三,男,25
custom.config.nested-arrays[1]=李四,女,23
custom.config.nested-arrays[2]=王五,男,27
  1. 业务代码中直接注入配置类使用即可
@Autowired
private NestedArrayConfig nestedArrayConfig;

// 取值示例:nestedArrayConfig.getNestedArrays() 即可得到List<String[]>对象

内容的提问来源于stack exchange,提问作者korallo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:45:03