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)

相关推荐
霸道流氓气质2 小时前
SpringBoot+MybatisPlus+自定义注解+切面实现水平数据隔离功能(附代码下载)
java·spring boot·后端
韩立学长2 小时前
【开题答辩实录分享】以《智慧校园勤工俭学信息管理系统的设计与实现》为例进行答辩实录分享
vue.js·spring boot·微信小程序
克莱恩~莫雷蒂2 小时前
Spring Boot 中 controller层注解
java·spring boot·后端
fouryears_234176 小时前
Redis缓存更新策略
java·spring boot·redis·spring
ChildrenGreens6 小时前
开箱即用的 Web 层解决方案:web-spring-boot-starter 助你统一返回体、异常处理与跨域配置
spring boot
计算机学姐6 小时前
基于SpringBoo+Vue的医院预约挂号管理系统【个性化推荐算法+可视化统计】
java·vue.js·spring boot·mysql·intellij-idea·mybatis·推荐算法
计算机学姐6 小时前
基于微信小程序的奶茶店点餐平台【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
L.EscaRC6 小时前
Spring Boot 事务管理深度解析
java·spring boot·spring
海边夕阳20067 小时前
数据源切换的陷阱:Spring Boot中@Transactional与@DS注解的冲突博弈与破局之道
java·数据库·spring boot·后端·架构
qq_2500568688 小时前
springboot接入企业微信群机器人消息推送
spring boot·机器人·企业微信