如何在 Spring Boot 2.6.4 中使用 @ConfigurationProperties 的记录(class 可能不是最终版本)

How to use records for @ConfigurationProperties in Spring Boot 2.6.4 (class may not be final)

我有一个漂亮的香草 Spring Boot v2.6.4 Java 应用程序,使用 Java 17.

我正在尝试让记录为我的@ConfigurationProperties 工作,但收效甚微。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "custom")
@ConstructorBinding
public record CustomConfigProperties(String path) { }

这失败了: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: @Configuration class 'CustomConfigProperties' may not be final. Remove the final modifier to continue.

显然,记录隐式是最终的,所以我很困惑。谷歌搜索再多也搜不出任何有用的东西。我能找到的最接近的是这个 问题,但它并没有真正直接相关事实上那里的评论者和我有同样的问题)

如果我明确注释我的主应用程序 class,它会起作用:

@ConfigurationPropertiesScan

这很荒谬,因为没有此注释的普通旧 class 样式也能工作。

@Configuration 应该用在通过 @Bean 方法定义 bean 的 class 上。使用 @Configuration 注释会触发 CGLib 代理的创建,以拦截这些 @Bean 方法之间的调用。正是这种代理尝试失败了,因为记录隐式是最终的。

您应该从您的记录中删除 @Configuration,然后使用 @ConfigurationPropertiesScan@EnableConfigurationProperties(CustomConfigProperties.class) enable your @ConfigurationProperties record。您还可以删除 @ConstructorBinding,因为记录是隐式构造函数绑定的。 @ConstructorBinding 仅在记录具有多个构造函数时才需要在记录上使用,并且您需要指示应将哪个构造函数用于 属性 绑定。