@ConfigurationProperties的多个前缀

时间:2020-09-15 07:56:41

标签: spring spring-boot spring-annotations

我有一个 application.properties 文件,其中包含以下内容。

server.name
server.id
server.ipadd

,并且我正在使用以下注释读取 configProperties.java

@ConfigurationProperties(prefix = "server")
private String name;
private String ipadd;

现在,我包括了其他属性。

server.client.type
server.client.location

,并想阅读这些新属性。如何在同一 configProperties.java 文件中阅读这些内容? 寻找类似以下格式的东西,其中包括多个前缀,我知道这些都是无效的。

 @ConfigurationProperties(prefix = "server", prefix = "server.client")
or
@ConfigurationProperties(prefix = "server")
@ConfigurationProperties(prefix = "server.client")

3 个答案:

答案 0 :(得分:1)

您需要创建一个新的类,例如

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pyarrow/table.pxi", line 858, in pyarrow.lib.RecordBatch.from_pandas
  File "/mnt/e/miniconda/envs/pandas/lib/python3.7/site-packages/pyarrow/pandas_compat.py", line 579, in dataframe_to_arrays
    for c, f in zip(columns_to_convert, convert_fields)]
  File "/mnt/e/miniconda/envs/pandas/lib/python3.7/site-packages/pyarrow/pandas_compat.py", line 579, in <listcomp>
    for c, f in zip(columns_to_convert, convert_fields)]
  File "/mnt/e/miniconda/envs/pandas/lib/python3.7/site-packages/pyarrow/pandas_compat.py", line 559, in convert_column     
    result = pa.array(col, type=type_, from_pandas=True, safe=safe)
  File "pyarrow/array.pxi", line 265, in pyarrow.lib.array
  File "pyarrow/array.pxi", line 80, in pyarrow.lib._ndarray_to_array
TypeError: an integer is required (got type str)

,并在带有服务器前缀的配置中添加它

public class ClientProperties {
   private String type;
   private String location;
}

答案 1 :(得分:0)

回答您关于

的问题 <块引用>

configProperties.getClientProperties().getLocation()

我不得不处理类似的事情,您可以将该调用包装在如下所示的 ConfigProperties 类中:

@ConfigurationProperties
public ConfigProperties{
    private String name;
    private String ipadd;
    private ClientProperties client;
    public static class ClientProperties {
       private String type;
       private String location;
    }
    public String getType(){return client.getType();}
}

所以你的内部结构是正确的,但是你可以从顶级类访问属性。就我而言,我使用的是无法重新格式化的生成的 git 属性,这比重新生成文件更容易。

答案 2 :(得分:0)

这是您尝试执行的操作的示例。

@Configuration
public class MultipleConfigPrefixExample {
  @Bean
  @ConfigurationProperties(prefix = "config.first.part")
  public FirstPart getFirstPart(){
    return new FirstPart();
  }

  @Bean
  @ConfigurationProperties(prefix = "info.another.part")
  public AnotherPart getAnotherPart(){
    return new AnotherPart();
  }

  @Getter
  @Setter
  public static class FirstPart {
    private String element1;
    private String element2;
  }


  @Getter
  @Setter
  public static class AnotherPart {
    private String element1;
    private String element2;
  }
}

注释 @Getter @Setter 来自龙目岛。