在spring中一起使用@ConfigurationProperties和@Value时出现问题

问题描述 投票:0回答:1

我正在使用

@ConfigurationProperties
@Value
都具有记录级别
[Java 21 & Spring boot starter 3.2.2]
。但是带有
@Value
的属性填充为空。我遇到了一些解释嵌套属性场景的线程 - Spring Inject Values with @ConfigurationProperties and @Value

任何人都可以帮助我理解为什么这对我不起作用吗?

application.yaml

abc:
  property1: value1
  property_name2: value2

记录

@ConfigurationProperties(prefix = "abc")
public record Model(
   String property1,
   @Value("${property_name2}") String property2) {
}

输出:

Model[property1=value1, property2=null]
java spring spring-boot
1个回答
0
投票

正如 @M.Deinum 在评论中所解释的,你不能将

@ConfigurationProperties
@Value
一起使用。

我认为您不能只重命名属性文件中的属性(或模型记录中的字段)是有充分理由的。

我想出了几个选项来解决您的问题:

选项1: 添加一个“getter”来检索 property2,它实际上使用

propertyName2

@ConfigurationProperties(prefix = "abc")
public record Model2(String property1, String propertyName2) {
    public String property2() {
        return propertyName2;
    }
}

选项 2: 将模型记录更改为组件,并使用

@Value
注入属性文件中的值。

@Component
public record Model(
        @Value("${abc.property1}")
        String property1,
        @Value("${abc.property_name2}")
        String property2) {
}

选项3: 将模型更改为类并使用构造函数绑定将属性映射到属性

@ConfigurationProperties(prefix = "abc")
public class Model3 {

    private final String property1;
    private final String property2;

    @ConstructorBinding
    public Model3(String property1, String propertyName2) {
        this.property1 = property1;
        this.property2 = propertyName2; // Map propertyName2 to property2
    }

    public String getProperty1() {
        return property1;
    }

    public String getProperty2() {
        return property2;
    }
}

您还可以在

@ConfigurationProperties
方法上使用
@Bean
来创建模型记录的实例,但我认为这最终会变得太麻烦,并且实际上仅适用于您确实无法编辑模型类的情况。

© www.soinside.com 2019 - 2024. All rights reserved.