首页 > 解决方案 > 如何在 Spring Boot 中从根键读取值

问题描述

我正在尝试从 rootKey 读取应用程序配置,但我得到了空值。

rootKey1:
   childKey1: childValue1
   childKey2: childValue2
   childKey3: childValue3

rootKey2:
   childKey1: childValue1
   childKey2: childValue2
   childKey3: childValue3

Environment environment;
getProperty(String key) {
   environment.getProperty(key+".childKey1"); --> is giving childValue1
-------------------
   environment.getProperty(key); --> is giving null
}

更正: rootKey 是动态的。

标签: javaspringspring-bootspring-cloud-config

解决方案


尝试定义您的属性对象结构并注册一个适当的 bean。

配置自定义数据源

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {

    @Data
    public static class RootProperty {

        private List<ChildProperty> list;
    }

    @Data
    public static class ChildProperty {

        private String name;
        private String childKey1;
        private String childKey2;
        private String childKey3;
    }

    @Autowired
    private ApplicationContext context;

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

    @Bean
    @ConfigurationProperties("root-key")
    public RootProperty rootProperty() {
        return new RootProperty();
    }

    @Override
    public void run(ApplicationArguments args) {
        System.out.println(context.getBean("rootProperty"));
    }
}

应用程序.yml

root-key:
  list:
    - name: child-key1
      childKey1: childValue1-1
      childKey2: childValue1-2
      childKey3: childValue1-3
    - name: child-key2
      childKey1: childValue2-1
      childKey2: childValue2-2
      childKey3: childValue2-3

推荐阅读