java Spring-boot:将默认值设置为可配置属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30882541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring-boot: set default value to configurable properties
提问by Ashvin Kanani
I have a properties class below in my spring-boot project.
我的 spring-boot 项目下面有一个属性类。
@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
private String property1;
private String property2;
// getter/setter
}
Now, I want to set default value to some other property in my application.properties file for property1
. Similar to what below example does using @Value
现在,我想在我的 application.properties 文件中为property1
. 类似于下面的例子使用@Value
@Value("${myprefix.property1:${somepropety}}")
private String property1;
I know we can assign static value just like in example below where "default value" is assigned as default value for property
,
我知道我们可以像下面的例子一样分配静态值,其中“默认值”被分配为默认值property
,
@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
private String property1 = "default value"; // if it's static value
private String property2;
// getter/setter
}
How to do this using @ConfigurationProperties class (rather typesafe configuration properties) in spring boot where my default value is another property ?
如何在 Spring Boot 中使用 @ConfigurationProperties 类(而不是类型安全的配置属性)来做到这一点,其中我的默认值是另一个属性?
回答by jst
Check if property1 was set using a @PostContruct in your MyProperties class. If it wasn't you can assign it to another property.
检查是否在 MyProperties 类中使用 @PostContruct 设置了 property1。如果不是,您可以将其分配给另一个属性。
@PostConstruct
public void init() {
if(property1==null) {
property1 = //whatever you want
}
}
回答by Andy Brown
In spring-boot 1.5.10 (and possibly earlier) setting a default value works as-per your suggested way. Example:
在 spring-boot 1.5.10(可能更早)中,设置默认值按照您建议的方式工作。例子:
@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
@Value("${spring.application.name}")
protected String appName;
}
The @Value
default is only used if not overridden in your own property file.
的@Value
,如果在你自己的属性文件没有覆盖默认时才使用。