我的 spring-boot 项目中有一个属性类如下。
@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
private String property1;
private String property2;
// getter/setter
}
现在,我想为 application.properties 文件中的其他一些属性设置默认值property1
。类似于下面使用 @Value 的示例
@Value("${myprefix.property1:${somepropety}}")
private String property1;
我知道我们可以分配静态值,就像下面的示例一样,其中“默认值”被分配为默认值property
,
@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
private String property1 = "default value"; // if it's static value
private String property2;
// getter/setter
}
如何在 Spring Boot 中使用 @ConfigurationProperties 类(而不是类型安全的配置属性)来执行此操作,其中我的默认值是另一个属性?
检查是否在 MyProperties 类中使用 @PostContruct 设置了 property1。如果不是,您可以将其分配给其他财产。
@PostConstruct
public void init() {
if(property1==null) {
property1 = //whatever you want
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)