在春季启动中将多个配置树变为一类

时间:2020-03-13 13:13:09

标签: java spring spring-boot yaml

我在Application.yaml中具有此功能:

  override:
    email:
      enabled: true
      value: "test@mycompany.com"
    phone:
      enabled: true
      value: "+420666666666"

如何使用这些值进行单个类配置? 我尝试过:

public class RecipientOverrideConfig {

    @Configuration
    @ConfigurationProperties("override.email")
    @Data
    public class EmailOverride{

        Boolean enabled;
        String value;

    }

    @Configuration
    @ConfigurationProperties("override.phone")
    @Data
    public class SmsOverride{

        Boolean enabled;
        String value;

    }
}

但是有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

我建议将整个班级设为ConfigurationProperties

@ConfigurationProperties("override")
public class RecipientOverrideProperties {
    private OverrideConfig email;
    private OverrideConfig phone;

    public class OverrideConfig {
        private Boolean enabled;
        private String value;
    }

    // getters and setters were omitted for brevity
}

然后将其自动连接到您的配置中:

@Configuration
public class RecipientOverrideConfig {
    @Autowired // or even better, use constructor injection
    private RecipientOverrideProperties overrideProperties;
}