Spring-boot:将默认值设置为可配置属性

Ash*_*ani 20 java properties configurationproperty spring-boot

我的spring-boot项目中有一个属性类.

@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
    private String property1;
    private String property2;

    // getter/setter
}
Run Code Online (Sandbox Code Playgroud)

现在,我想将默认值设置为application.properties文件中的其他属性property1.类似于以下示例使用@Value

@Value("${myprefix.property1:${somepropety}}")
private String property1;
Run Code Online (Sandbox Code Playgroud)

我知道我们可以像下面的示例一样分配静态值,其中"默认值"被指定为默认值property,

@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
    private String property1 = "default value"; // if it's static value
    private String property2;

    // getter/setter
}
Run Code Online (Sandbox Code Playgroud)

如何在spring boot中使用@ConfigurationProperties类(而不是类型安全的配置属性)来执行此操作,其中我的默认值是另一个属性?

jst*_*jst 8

检查是否在MyProperties类中使用@PostContruct设置了property1.如果不是,您可以将其分配给另一个属性.

@PostConstruct
    public void init() {
        if(property1==null) {
            property1 = //whatever you want
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 这解决了我现在的问题.但是,我认为spring应该像@Value一样为它提供支持. (5认同)

And*_*own 5

在spring-boot 1.5.10(可能更早)中,按照您建议的方式设置默认值即可。例:

@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {

  @Value("${spring.application.name}")
  protected String appName;
}
Run Code Online (Sandbox Code Playgroud)

@Value,如果在你自己的属性文件没有覆盖默认时才使用。