【问题标题】:How to read property as List<String> from [] in springboot如何在 Spring Boot 中从 [] 读取属性为 List<String>
【发布时间】:2021-07-17 10:40:41
【问题描述】:

有时我看到有人在属性文件中这样定义:

spring.autoconfigure.exclude[0]=com.vietnam.AAutoConfiguration
spring.autoconfigure.exclude[1]=com.vietnam.BAutoConfiguration

只是问题:如何在 Spring bean 中定义一个属性来收集这个配置作为列表? 在其他地方,他们说这样使用: 在属性中:

spring.autoconfigure.exclude=com.vietnam.AAutoConfiguration,com.vietnam.BAutoConfiguration

春豆里

@Value("#{'${spring.autoconfigure.exclude}'.split(',')}"

但我不喜欢这种方式,以防价值很长。每行一个配置会更容易阅读和维护

谢谢

【问题讨论】:

    标签: spring spring-boot properties


    【解决方案1】:

    您可以读取多个字符串,如下所示 在 application.properties 中

    app.names=vipul,uncle,bob
    

    在你的组件类中

    @Value("${app.names}")
    private List<String> names;
    

    【讨论】:

    • 确定如果值是短文本也没问题。但我不喜欢在某些长值情况下使用逗号。不易维护
    【解决方案2】:

    我找到了方法,使用 @Value 将不支持我想要的案例。 我们需要使用 @ConfigurationProperties 然后 Spring 将收集属性作为列表

    @ConfigurationProperties(prefix = "spring.autoconfigure")
    public class SpringConfig {
      @Setter //lombok
      private List<String> exclude;
    }
    

    配置简单如下:

    spring.autoconfigure.exclude[0]=com.vietnam.AAutoConfiguration
    spring.autoconfigure.exclude[1]=com.vietnam.BAutoConfiguration
    

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 2020-04-27
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 2016-04-29
      • 2018-10-16
      • 2015-08-11
      • 2019-07-23
      相关资源
      最近更新 更多