Java 17中Record与@ConfigurationProperties使用报错及解决方法
问题原因
这个报错的核心是Spring未正确识别EnvironmentConstants为配置属性类,反而将其当作普通Bean处理,尝试自动注入构造参数String myConstant,但Spring容器中不存在匹配的String类型Bean,因此抛出依赖不满足异常。
解决方案
针对Java 17 + Spring Boot 3.2.4环境下,使用Record结合@ConfigurationProperties的正确配置方式有两种:
方案一:使用@ConfigurationPropertiesScan
- application.yml 配置
确保配置前缀与Record类的@ConfigurationProperties前缀匹配:
app: environment-constants: my-constant: 'MyValue'
- Record 配置类
为Record添加@ConfigurationProperties注解,指定对应配置前缀:
@ConfigurationProperties(prefix = "app.environment-constants") public record EnvironmentConstants(String myConstant) { }
- 启动类配置
在启动类添加@ConfigurationPropertiesScan注解,触发Spring扫描配置属性类:
@SpringBootApplication @ConfigurationPropertiesScan public class RecordConfigurationPropertiesTestApplication { public static void main(String[] args) { SpringApplication.run(RecordConfigurationPropertiesTestApplication.class, args); } }
方案二:使用@EnableConfigurationProperties
无需扫描,直接在启动类指定要启用的配置属性类:
@SpringBootApplication @EnableConfigurationProperties({EnvironmentConstants.class}) public class RecordConfigurationPropertiesTestApplication { public static void main(String[] args) { SpringApplication.run(RecordConfigurationPropertiesTestApplication.class, args); } }
两种方案配置完成后,即可在测试类或其他组件中正常注入EnvironmentConstants并读取配置值。
内容的提问来源于stack exchange,提问作者Alexxxx
相关产品推荐
相关产品推荐

