spring-boot - @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
中。
我在这里想念什么?
解决方案
你不应该混和@Value
在@ConfigurationProperties
同一个班级。如果要在带@ConfigurationProperties
注释的类中使用默认值,可以使用默认值配置字段:
@ConfigurationProperties("foo")
public class FooConfig {
private Integer iterations = 999;
// getter / setter
}
此更改带来了额外的好处,即在生成的元数据中包含默认值spring-boot-configuration-processor
。IDE 使用元数据在您编辑application.properties
和application.yaml
文件时提供自动完成功能。
最后,与您的问题没有直接关系,带@ConfigurationProperties
注释的类不应使用@Configuration
. @Configuration
-annotated 类用于通过方法配置bean @Bean
。你的FooConfig
类应该被注释@Component
或者你应该在想要使用@EnableConfigurationProperties(FooConfig.class)
的类上使用.@Configuration
FooConfig
推荐阅读
- java - 如何在 ScreenSlidePagerAdapter 中启动新活动?
- java - JasperReports 在 iOS 12 上的权限问题
- javascript - 如何从 JS AJAX 请求中获取 PHP 变量?
- python - (500 Internal Server Error])Flask Post 请求导致服务器错误 [Flask]
- reactjs - AWS Lambda 和 .Net Core WebAPI 出现 Cors 错误
- css - CSS:线性渐变背景颜色不适用
- java - 错误:不兼容的类型:Fragment 无法转换为 SupportMapFragment
- ios - 如何在IOS App swift上去除顶部栏的透明度
- c# - 为什么当输入与typof(X).GetFullName 完全相同的输入时,Type.GetType 不返回类型?
- java - 实例化 Java AWT 对象会导致在 macOS 上打开空应用程序