繁体   English   中英

使用 @Value 从 Spring Boot 中的应用程序 YML 创建带有列表的地图

[英]Create Map with List from application YML in Spring Boot using @Value

我正在尝试在 Java 服务中创建一个Map<Integer,List<Integer>>变量。

我有这个.yml:

my:
  data:
    '{
      1:[1,2,3],
      2:[1,2,3]
    }'

并进入 Java 代码:

@Value("#{${my.data}}")
protected Map<Integer,List<Integer>> bar;

但是当我运行项目时它失败了。

实际上抛出的错误是这样的:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controller' defined in file ...

但它必须通过依赖注入,在@Service创建@Value时失败并且错误被传播。 我也测试了这些值

my:
  data:
    '{
      1:
      - 1
      - 2,
      2:
      - 1
    }'

它创建了一个值为-3-1的列表。

| key | value |
+-----+-------+
|  1  |  [-3] |
|  2  |  [-1] |
+-----+-------+

所以之前抛出的错误必须是由于第一个yml列表的定义。

我还测试了使用List<Integer>int[]Map对象中。

那么,创建Map<Integer, List<Integer>>的正确语法是什么? 我认为它就像一个 JSON 对象{ key: [v1, v2] }但它似乎失败了。

提前致谢。

使用@Value注释:

  1. 您不应该将(yaml 或属性“映射”)键映射到Integer ,而更喜欢String

  2. (问题)嵌套列表...

..仍然,我很确定 (crazy SpEL(l) @Value ) 是可能的。

baeldung-文章


但是类型安全的配置属性很快就会产生很好的结果:

应用程序.java:

@SpringBootApplication
@ConfigurationPropertiesScan
public class App {

  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }

  @Bean
  CommandLineRunner runner(@Autowired My bar) {
    return args ->  System.out.println(bar);
  }
}

我的.java:

@ConfigurationProperties("my")
public class My {
    private Map<Integer, List<Integer>> data = new HashMap<>();
    // Getter + Setter!!!
}

有了这个“固定”的yaml:

my:
  data: {
    1: [1,2,3],
    2: [1,2,3]
  }

印刷:

My(data={1=[1, 2, 3], 2=[1, 2, 3]})

(jdk:8, maven:3.8.2, spring-boot:2.5.6)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM