【问题标题】:Reading property values in constructor using prefix使用前缀读取构造函数中的属性值
【发布时间】:2020-05-19 13:52:00
【问题描述】:

如何在下面的代码中使用前缀?

属性:

height.customer.feet=10

height.customer.eu.timezone=UTC

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "height.customer")
public class Customer {

    private final int age;

    private final String timezone;

    public Customer(int age, String timezone){
        this.age = age;
        this.timezone = timezone;
    }
}

在这里,我想为年龄和时区设置默认值。默认值从 application.properties 文件中读取。有人可以帮帮我吗?

我可以像下面这样使用。

    @Value("${height.customer.age}")
    private final int age;

    @Value("${height.customer.eu.timezone}")
    private final String timezone;

但如果我这样使用,我可能无法使用构造函数注入

【问题讨论】:

  • 为什么需要构造函数注入?值年龄和时区将正常使用“@ConfigurationProperties”或“@Value”填充。

标签: spring spring-boot spring-mvc spring-data


【解决方案1】:

@ConfigurationProperties@Value 注释之间没有关系。检查here。您应该使用的是 @PropertySource 注释。如果你使用@ConfigurationProperties,那么你应该有分层属性

@Configuration
@ConfigurationProperties(prefix = "height.customer")
public class Customer {

    private final int age;  // This maps to height.customer.age

    private final String timezone; // This does NOT map to height.customer.eu.timezone but maps to height.customer.timezone

    public Customer(int age, String timezone){
        this.age = age;
        this.timezone = timezone;
    }
}

在这个例子中使用@PropertySource

@Configuration
@PropertySource("classpath: demo.properties") // your properties file
public class Customer {

    @Value("${height.customer.age}")
    private final int age;

    @Value("${height.customer.eu.timezone}")
    private final String timezone;

    public Customer(int age, String timezone){
        this.age = age;
        this.timezone = timezone;
    }

    public Customer(){}
}

并且不会与现有构造函数发生冲突,因为通过@PropertySource 注入的值将是默认值。如果您在构造函数中提供值,这些值将被覆盖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多