我有一个配置类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
and @ConfigurationProperties
在同一个班。如果您想在 a 中使用默认值@ConfigurationProperties
- 带注释的类,可以使用默认值配置字段:
@ConfigurationProperties("foo")
public class FooConfig {
private Integer iterations = 999;
// getter / setter
}
此更改带来了额外的好处,即在生成的元数据中包含默认值spring-boot-configuration-processor
。 IDE 使用元数据在您编辑时提供自动完成功能application.properties
and application.yaml
files.
最后,与您的问题没有直接关系,@ConfigurationProperties
-带注释的类不应注释为@Configuration
. An @Configuration
- 带注释的类用于通过以下方式配置bean@Bean
方法。你的FooConfig
类应该用注释@Component
或者你应该使用@EnableConfigurationProperties(FooConfig.class)
on the @Configuration
想要使用的类FooConfig
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)