首页 > 解决方案 > @ConfigurationProperties:绑定类中的默认值

问题描述

我有一个配置类FooConfig,其中我有一个绑定类“Foo”。

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

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

  private Foo foo;

  // getter / setter

}

在我的课程Foo中,当没有在属性文件中明确设置时,我希望使用现有默认配置值设置迭代变量。

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中。

我在这里想念什么?

标签: spring-boot

解决方案


你不应该混和@Value@ConfigurationProperties同一个班级。如果要在带@ConfigurationProperties注释的类中使用默认值,可以使用默认值配置字段:

@ConfigurationProperties("foo")
public class FooConfig {

    private Integer iterations = 999;

    // getter / setter

}

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

最后,与您的问题没有直接关系,带@ConfigurationProperties注释的类不应使用@Configuration. @Configuration-annotated 类用于通过方法配置bean @Bean。你的FooConfig类应该被注释@Component或者你应该在想要使用@EnableConfigurationProperties(FooConfig.class)的类上使用.@ConfigurationFooConfig


推荐阅读