【问题标题】:Kotlin constructor binding is not applicable to target 'class'Kotlin 构造函数绑定不适用于目标 \'class\'
【发布时间】:2022-12-31 01:02:13
【问题描述】:

我是科特林的新手。我正在尝试实现同样的事情,我会用 Java 做。

在 application.yaml 中,我有这个配置:

conference:
 plans:
   - plan-id: P1_1
     product-id: product1
     employee-limit: 50
   - plan-id: P1_2
     product-id: product2
     employee-limit: 100

然后我想创建数据类,这样,当我运行 springboot 应用程序时,这个类会自动加载和验证

在 Conferences.kt 文件中:

package com.company.conferenceplanservice.config.properties

import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotEmpty
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.bind.ConstructorBinding
import org.springframework.context.annotation.Configuration
import org.springframework.validation.annotation.Validated

@Validated
@ConstructorBinding
@Configuration
@ConfigurationProperties(prefix = "conference")
data class Plans(
    @field:NotEmpty val plans: Set<Plan>
)

@Validated
@ConstructorBinding
data class Plan(
    @field:NotBlank val planId: String,
    @field:NotBlank val productId: String,
    val eomployeeLimit: Int
)

但它总是在写入 ConstructorBinding 的两个地方抛出这个异常

Kotlin:此注释不适用于目标“类”

springboot 3.0.0,java 18,kotlin 1.7.21

【问题讨论】:

    标签: spring-boot kotlin


    【解决方案1】:

    我不使用 Spring,但我猜 @ConstructorBinding 是构造函数的注释。您在类声明本身上使用它。这就像在 Java 中把它放在类名前面:

    @ConstructorBinding
    public class Plans {
    
        //...
    
    }
    

    如果要在 Kotlin 中注释数据类构造函数,则必须声明构造函数。您省略了 constructor 关键字,这通常很好,但如果您需要对其进行注释或修改其可见性,则不能这样做:

    @Validated
    @Configuration
    @ConfigurationProperties(prefix = "conference")
    data class Plans
    @ConstructorBinding constructor(
        @field:NotEmpty val plans: Set<Plan>
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多