springboot 注入配置文件中的集合 List

在使用 springboot 开发时,例如你需要注入一个 url 白名单列表,你可能第一想到的写法是下面这样的:

application.yml

yml 复制代码
white.url-list:
  - /test/show1
  - /test/show2
  - /test/show3
java 复制代码
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Value("${white.url-list}")
    private List<String> whileUrlList;

    @GetMapping("/show1")
    public Mono<String> show1(){
        log.info("whileUrlList={}", whileUrlList);
        return Mono.just("OK");
    }

}

然而,我们天真的以为,这样是没有问题的,实际不然,这是一种错误的行为,本文截稿时 Spring 还是不支持直接使用 @Value 的方式注入集合的。
这种需求查看了官网ISSUE,从2014年(甚至更早)就被很多人提出,很遗憾的是官方至今没有对这种注入方式进行支持。

那么我们如何注入集合呢,这里我们需要使用 @ConfigurationProperties 的方式来达到目的,具体的代码如下:

1、添加依赖

xml 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

2、application.yml 配置文件

yml 复制代码
white.url-list:
  - /test/show1
  - /test/show2
  - /test/show3

3、创建对应的Java对象

java 复制代码
@Data
@Component
@ConfigurationProperties(prefix = "white")
public class WhiteUrlProperties {

    private List<String> urlList;

}

4、注入Java对象使用

java 复制代码
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private WhiteUrlProperties whileUrlList;

    @GetMapping("/show1")
    public Mono<String> show1(){
        log.info("whileUrlList={}", whileUrlList.getUrlList());
        return Mono.just("OK");
    }

}

如果实在不想单独出来一个Java类,你直接把 @ConfigurationProperties 添加到你的 Service、Controller 等 SpringBean 的 Java 类上也是可以的,但是要注意一定要有对应的 set 方法(否则失败),如下代码所示:

java 复制代码
@Slf4j
@RestController
@RequestMapping("/test")
@ConfigurationProperties("white")
public class TestController {

    private List<String> urlList;

    @GetMapping("/show1")
    public Mono<String> show1(){
        log.info("whileUrlList={}", urlList);
        return Mono.just("OK");
    }

    public void setUrlList(List<String> urlList) {
        this.urlList = urlList;
    }
}

(END)

相关推荐
雨白1 小时前
使用 Kotlin 与 Spring Boot 从零搭建 Web 应用
spring boot·kotlin
一 乐1 小时前
交通感知与车路协同系统|基于springboot + vue交通感知与车路协同系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·交通感知与车路协同系统
uElY ITER1 小时前
基于Spring Boot 3 + Spring Security6 + JWT + Redis实现登录、token身份认证
spring boot·redis·spring
book123_0_992 小时前
Spring Boot 条件注解:@ConditionalOnProperty 完全解析
java·spring boot·后端
NCIN EXPE2 小时前
使用Springboot + netty 打造聊天服务(一)
java·spring boot·后端
MXN_小南学前端2 小时前
Vue3 + Spring Boot 工单系统实战:用户反馈和客服处理的完整闭环(提供gitHub仓库地址)
前端·javascript·spring boot·后端·开源·github
smileNicky3 小时前
Spring AI系列之基于MCP协议实现天气预报工具插件
人工智能·spring boot·spring
一條狗3 小时前
学习日报 20260423|[特殊字符] 深度解析:Vue 3 SPA 部署到 Spring Boot 的 404/500 错误排查与完美解决方案-2
vue.js·spring boot·学习
青槿吖3 小时前
第二篇:从复制粘贴到自定义规则!Spring Cloud Gateway 断言 + 过滤全玩法,拿捏微服务流量管控
java·spring boot·后端·spring cloud·微服务·云原生·架构
wljt4 小时前
SpringBoot学习笔记五:Spring Boot的web开发
spring boot·笔记·学习