23

我的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 类(而不是类型安全的配置属性)来做到这一点?

4

2 回答 2

8

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

@PostConstruct
    public void init() {
        if(property1==null) {
            property1 = //whatever you want
        }
    }
于 2015-06-17T16:32:34.333 回答
4

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

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

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

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

于 2018-05-01T13:43:06.543 回答