嵌套类中的ConfigurationProperties

时间:2019-12-03 10:26:46

标签: spring spring-boot

带有以下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来说,这两个类具有相同的值。

我该如何解决?

2 个答案:

答案 0 :(得分:1)

我发现了问题。只是。 yml doesn't work with 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 {
    }
}

它奏效了。

答案 1 :(得分:0)

您可以使用列表作为配置参数:

ERROR: invalid transaction termination
  Where: PL/pgSQL function MyFunction line 185 at COMMIT  Call getNextException to see other errors in the batch. Line 185 at COMMIT  Call getNextException to see other errors in the batch.

并在一个单独的bean中以更复杂的方式获取您的价值:

app:
  props: 
    - key: a
      value: aaa

    - key: b
      value: bbb

将其注入您的Common类实现中:

@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
    }
}