Kotlin中@ConstructorBinding标注类报错:不适用于class目标
问题解决步骤
1. 修正@ConstructorBinding的使用方式
@ConstructorBinding注解的作用目标是构造函数,而非类,直接标注在类上会触发语法错误。对于Kotlin数据类,需要将其标注在主构造函数上:
@Validated @ConfigurationProperties(prefix = "conference") data class Plans @ConstructorBinding constructor( @field:NotEmpty @field:Valid // 触发嵌套Plan对象的验证逻辑 val plans: Set<Plan> ) @Validated data class Plan @ConstructorBinding constructor( @field:NotBlank val planId: String, @field:NotBlank val productId: String, val employeeLimit: Int // 修正拼写错误:原eomployeeLimit → employeeLimit )
2. SpringBoot 3.0+ 可直接省略@ConstructorBinding
从SpringBoot 3.0开始,只要配置属性类的所有属性用val声明(不可变),Spring会自动启用构造函数绑定,无需手动添加@ConstructorBinding:
@Validated @ConfigurationProperties(prefix = "conference") data class Plans( @field:NotEmpty @field:Valid val plans: Set<Plan> ) @Validated data class Plan( @field:NotBlank val planId: String, @field:NotBlank val productId: String, val employeeLimit: Int )
3. 调整配置类的注册方式
移除Plans类上的@Configuration注解,改为在SpringBoot主启动类中通过@EnableConfigurationProperties注册配置属性类:
@SpringBootApplication @EnableConfigurationProperties(Plans::class) class ConferencePlanServiceApplication fun main(args: Array<String>) { runApplication<ConferencePlanServiceApplication>(*args) }
4. 确保依赖齐全
需要在项目依赖中加入验证启动器,以支持@NotBlank、@NotEmpty等注解的校验逻辑:
Gradle Kotlin DSL
dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter-validation") implementation("com.fasterxml.jackson.module:jackson-module-kotlin") implementation("org.jetbrains.kotlin:kotlin-reflect") }
Maven
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-kotlin</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-reflect</artifactId> </dependency> </dependencies>
关键注意事项
- 必须修正
Plan类中属性的拼写错误:eomployeeLimit改为employeeLimit,否则无法与yaml配置中的employee-limit完成绑定。 - 在
plans属性上添加@Valid注解,才能触发嵌套Plan对象的校验规则。
内容的提问来源于stack exchange,提问作者curious
相关产品推荐
相关产品推荐

