@ConfigurationProperties:绑定类中的默认值 [英] @ConfigurationProperties: Default value in bound class

查看:36
本文介绍了@ConfigurationProperties:绑定类中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置类 FooConfig,其中我有一个绑定类Foo".

I have a config class FooConfig, in which i have a bound class 'Foo'.

@Configuration
@ConfigurationProperties("foo")
public class FooConfig {

  @Value("${foo.default.iterations}")
  private Integer iterations;

  private Foo foo;

  // getter / setter

}

在我的类 Foo 中,当未在属性文件中明确设置时,我希望迭代变量集具有现有的默认配置值.

In my class Foo I want the iterations-variable set with an existing default configuration-value, when not explicitly set in the properties-file.

public class Foo {

  private String name;

  @Value("${foo.default.iterations}")
  private Integer iterations;

  // getter / setter

}

我的属性文件

foo.default.iterations=999

# if this is set this config is bound (wins) in FooConfig-class as expected
# foo.iterations=111

foo.foo.name=foo

FooConfig 中设置默认值有效,但在我绑定的类 Foo 中无效.

Setting a default value in FooConfig works, but not in my bound class Foo.

我在这里遗漏了什么?

推荐答案

你不应该将 @Value@ConfigurationProperties 混合在同一个类中.如果您想在 @ConfigurationProperties 注释的类中有默认值,您可以使用默认值配置字段:

You shouldn't mix @Value and @ConfigurationProperties in the same class. If you want to have default values in a @ConfigurationProperties-annotated class, you can configure the fields with a default value:

@ConfigurationProperties("foo")
public class FooConfig {

    private Integer iterations = 999;

    // getter / setter

}

此更改带来了额外的好处,即在 spring-boot-configuration-processor 生成的元数据中包含默认值.当您编辑 application.propertiesapplication.yaml 文件时,IDE 会使用元数据提供自动完成功能.

This change brings with it the added benefit of including the default value in the metadata that's generated by spring-boot-configuration-processor. The metadata is used by your IDE to provide auto-completion when you're editing application.properties and application.yaml files.

最后,与您的问题没有直接关系的是,@ConfigurationProperties 注释的类不应使用 @Configuration 进行注释.@Configuration 注释类用于通过 @Bean 方法配置 bean.您的 FooConfig 类应该使用 @Component 进行注释,或者您应该在 @Configuration<上使用 @EnableConfigurationProperties(FooConfig.class)/code> 想要使用 FooConfig 的类.

Lastly, and not directly related to your problem, a @ConfigurationProperties-annotated class should not be annotated with @Configuration. An @Configuration-annotated class is used to configure beans via @Bean methods. Your FooConfig class should either be annotated with @Component or you should use @EnableConfigurationProperties(FooConfig.class) on the @Configuration class that wants to use FooConfig.

这篇关于@ConfigurationProperties:绑定类中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆