【问题标题】:Spring-boot: set default value to configurable propertiesSpring-boot:将默认值设置为可配置属性
【发布时间】:2015-06-17 04:49:47
【问题描述】:

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

【问题讨论】:

标签: java properties spring-boot configurationproperty


【解决方案1】:

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

@PostConstruct
    public void init() {
        if(property1==null) {
            property1 = //whatever you want
        }
    }

【讨论】:

  • 这暂时解决了我的问题。但是,我认为 spring 应该像 @Value 一样提供相同的支持。
  • 我正在搜索如何设置默认值,这大概是我能找到的唯一答案.. 但是on this wiki 似乎您可以像您期望的那样为您的属性设置默认值。跨度>
【解决方案2】:

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

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

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

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

【讨论】:

  • 谢谢,但是如何从属性文件中解析参数值呢?例如,如何确保特定值确实是整数并且在 5-8 的范围内?
  • @Xenonite:将@Validated 添加到类中,然后在字段上使用现有的javax.validation.constraints.* 注释,或者如果提供的内容不足,请创建一些自己的注释。
  • 不建议混合使用这两种行为。
猜你喜欢
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
相关资源
最近更新 更多