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)

相关推荐
rfidunion3 小时前
springboot+VUE+部署(12。Nginx和前端配置遇到的问题)
前端·vue.js·spring boot
FYKJ_20103 小时前
springboot大学校园论坛管理系统--附源码42669
java·javascript·spring boot·python·spark·django·php
QQ24391973 小时前
语言在线考试与学习交流网页平台信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·spring boot·sql·学习·java-ee
毕设源码-小云学姐3 小时前
计算机毕业设计springboot医疗档案管理系统 基于 SpringBoot 的电子医疗档案管理系统的设计与实现 SpringBoot 框架下的医疗档案信息化管理系统开发
spring boot·后端·课程设计
想不明白的过度思考者3 小时前
JavaEE进阶 ——【SpringBoot 快速上手】从环境搭建到HelloWorld实战
java·spring boot·spring·java-ee
那我掉的头发算什么3 小时前
【SpringBoot】一篇文章讲清楚拦截器所有知识
java·spring boot·后端·spring
百锦再5 小时前
Java中的反射机制详解:从原理到实践的全面剖析
java·开发语言·jvm·spring boot·struts·spring cloud·kafka
树码小子7 小时前
图书管理系统(5)强制登陆(后端实现)
spring boot·mybatis·图书管理系统
丹牛Daniel7 小时前
Java解决HV000183: Unable to initialize ‘javax.el.ExpressionFactory‘
java·开发语言·spring boot·tomcat·intellij-idea·个人开发
PHP源码9 小时前
SpringBoot实验室管理系统
spring boot·springboot实验室设备·java实验室预约设备管理·vue实验室预约设备管理系统·前后端分离实验室管理系统