Spring Boot读取YML配置文件报错问题求助
解决Spring Boot + Kotlin读取YML配置失败的问题
我来帮你排查这个问题!看起来核心问题出在YML配置的前缀缺失,再加上Kotlin配置类的一些细节没处理到位,咱们一步步解决:
1. 先修正YML配置的前缀
你注意到没?.properties文件里所有配置都带template.前缀,但YML里直接写了age、row这些根级属性,Spring根本没法把它们和你的TemplateProperties类关联起来!把YML改成带前缀的结构:
template: age: 2 row: 6 attributes: - tagname: tag type: string value: VALUE scopes: - one-scope - second-scope
2. 完善Kotlin配置类的注解与属性定义
你的配置类需要明确告诉Spring它对应的配置前缀,还要处理Kotlin里集合初始化的问题(避免未初始化的空指针),另外注意类型匹配(配置里的age是数字,别写成String啦)。给你一个完整的示例:
import javax.validation.constraints.NotNull import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.stereotype.Component @Component @ConfigurationProperties(prefix = "template") class TemplateProperties { @NotNull var age: Int = 0 // 配置里是数字,用Int更贴合,要是确实需要字符串就改成String var row: Int = 0 // 提前初始化集合,Spring注入时就不会有空指针问题了 var attributes: MutableList<Attribute> = mutableListOf() // 内部类定义attributes的结构,用data class更简洁 data class Attribute( var tagname: String? = null, var type: String? = null, var value: String? = null, var scopes: MutableList<String> = mutableListOf() ) }
3. 启用配置属性绑定
最后别忘了在Spring Boot的主类上加上@EnableConfigurationProperties注解,让Spring识别并处理你的配置类:
import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.EnableConfigurationProperties @SpringBootApplication @EnableConfigurationProperties(TemplateProperties::class) class YourApplication fun main(args: Array<String>) { runApplication<YourApplication>(*args) }
额外小提示
- 要是你用的是Spring Boot 2.2及以上版本,甚至可以去掉
@Component,只靠@ConfigurationProperties加@EnableConfigurationProperties就能生效 - 一定要用
var定义属性,Spring需要可写的属性来注入值,val是只读的没法注入 - 确认你的YML文件是
application.yml,放在src/main/resources目录下,Spring才能自动加载它
内容的提问来源于stack exchange,提问作者BadChanneler
相关产品推荐
相关产品推荐

