springboot 注入配置文件中的集合 List-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

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

application.yml

white.url-list:
  - /test/show1
  - /test/show2
  - /test/show3
@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、添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

2、application.yml 配置文件

white.url-list:
  - /test/show1
  - /test/show2
  - /test/show3

3、创建对应的Java对象

@Data
@Component
@ConfigurationProperties(prefix = "white")
public class WhiteUrlProperties {

    private List<String> urlList;

}

4、注入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 方法否则失败如下代码所示

@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

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring