简体   繁体   English

Spring Boot中嵌套外部配置类

[英]Nested external configuration classes in Spring Boot

I want to inject my application.yml into a nested Map like this:我想像这样将我的application.yml注入到嵌套的Map

application.yml应用.yml

components:
  component1:
    host: host1
    port: 1111
  component2:
    host: host2
    port: 2222
  component3:
    host: host3
    port: 3333

MyComponents.java我的组件.java

@Component
@ConfigurationProperties
public class MyComponents {
  Map<String, MyComponent> components;

  public class MyComponent {
    String host;
    Integer port;
    
    //empty constructor, getters, setters
  }

  //empty constructor, getters, setters
}

But even if I don't instantiate the object ( @Autowire ), I'm getting the following error message:但即使我没有实例化 object ( @Autowire ),我也会收到以下错误消息:

org.springframework.beans.NullValueInNestedPathException: Invalid property 'components[component1]' of bean class [package.path.MyComponents]: Could not instantiate property type [package.path.MyComponents$MyComponent] to auto-grow nested property path: java.lang.InstantiationException: package.path.MyComponents$MyComponent org.springframework.beans.NullValueInNestedPathException:bean class [package.path.MyComponents] 的无效属性“components[component1]”:无法实例化属性类型 [package.path.MyComponents$MyComponent] 以自动增长嵌套属性路径:java .lang.InstantiationException: package.path.MyComponents$MyComponent

How do I get the configuration into my class layout?如何将配置放入我的 class 布局中?

The inner class MyComponent has to be static :内部class MyComponent必须是static

@Component
@ConfigurationProperties
public class MyComponents {
  Map<String, MyComponent> components;

  public static class MyComponent {
    String host;
    Integer port;
    
    //empty constructor, getters, setters
  }

  //empty constructor, getters, setters
}

This answer was posted as an edit to the question Nested external configuration classes in Spring Boot by the OP Squall under CC BY-SA 3.0.此答案作为对Spring 引导中嵌套外部配置类问题的编辑发布,由 CC BY-SA 3.0 下的 OP Squall提供。

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

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