Java Spring引导:将默认值设置为可配置属性

Java Spring引导:将默认值设置为可配置属性,java,properties,spring-boot,configurationproperty,Java,Properties,Spring Boot,Configurationproperty,我在我的spring boot项目中有一个属性类 @Component @ConfigurationProperties(prefix = "myprefix") public class MyProperties { private String property1; private String property2; // getter/setter } 现在,我想在我的application.properties文件中为property1设置一些其他属性的默认值

我在我的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;
我知道我们可以指定静态值,就像下面的示例一样,其中“默认值”被指定为
属性的默认值

@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类(而不是typesafe配置属性)实现这一点,其中我的默认值是另一个属性?

检查是否在MyProperties类中使用@PostContract设置了属性1。如果不是,您可以将其分配给其他属性

@PostConstruct
    public void init() {
        if(property1==null) {
            property1 = //whatever you want
        }
    }
在SpringBoot1.5.10(可能更早)中,设置默认值按照您建议的方式工作。例如:

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

  @Value("${spring.application.name}")
  protected String appName;
}

@Value
默认值仅在您自己的属性文件中未重写时使用。

这就解决了我的问题。但是,我认为spring应该像@Value一样提供相同的支持。我在搜索如何设置默认值,这大概是我能找到的唯一答案。。但是,您似乎可以像预期的那样为属性设置默认值。请查看以下问题:谢谢,但是如何以这种方式解析属性文件中的参数值?例如,我如何确保特定值确实是一个整数,并且在5-8范围内?@Xenonite:将
@Validated
添加到类中,然后在字段上使用现有的
javax.validation.constraints.*
注释,或者在提供的内容不足的情况下创建一些自己的注释。不建议将这两种行为混合使用。