Spring-boot:将默认值设置为可配置属性 [英] Spring-boot: set default value to configurable properties

查看:975
本文介绍了Spring-boot:将默认值设置为可配置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a properties class below in my spring-boot project.

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

    // getter/setter
}

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

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

@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,

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

    // getter/setter
}

怎么做这在春季启动时使用@ConfigurationProperties类(而不是类型安全的配置属性),我的默认值是另一个属性?

How to do this using @ConfigurationProperties class (rather typesafe configuration properties) in spring boot where my default value is another property ?

推荐答案

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

Check if property1 was set using a @PostContruct in your MyProperties class. If it wasn't you can assign it to another property.

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

这篇关于Spring-boot:将默认值设置为可配置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆