簡體   English   中英

嵌套類中的配置屬性

[英]ConfigurationProperties in nested classes

使用以下 yml

app:
  a:
    prop: aaa
  b:
    prop: bbb
@Component
public abstract class Common {

    @Value("${prop}")
    private String prop;

    @ConfigurationProperties(prefix = "app.a")
    @PropertySource("classpath:app.yml")
    @Component
    public static class A extends Common {
    }

    @ConfigurationProperties(prefix = "app.b")
    @PropertySource("classpath:app.yml")
    @Component
    public static class B extends Common {
    }
}

但是對於ab ,這兩個類具有相同的值。

我該如何解決這個問題?

我發現了問題。 簡單地。 yml不適用於PropertySource

我仍然想相信我是錯的。

我將.yml文件更改為properties並嘗試使用此方法。

@PropertySource("classpath:/vendor.properties")
@EnableConfigurationProperties
public abstract class Common {

    @Value("${prop}")
    private String prop;

    @ConfigurationProperties(prefix = "app.a")
    @Component
    public static class A extends Common {
    }

    @ConfigurationProperties(prefix = "app.b")
    @Component
    public static class B extends Common {
    }
}

它奏效了。

您可以使用配置參數列表:

app:
  props: 
    - key: a
      value: aaa

    - key: b
      value: bbb

並在單獨的 bean 中以更復雜的方式檢索您的價值:

@ConfigurationProperties(prefix = "app")
public class CommonConfiguration {
    List<Prop> props;
    //Getters and setters
    public Prop retreiveSpecificConfiguration(String className) {
        //some kind of logic here
    }

    public static class Prop {
      private String key, value;
      //Getters and setters
    }
}

將它注入您的 Common 類實現中:

@Autowired
CommonConfiguration config;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM