cur*_*ous 5 kotlin spring-boot
我是科特林新手。我正在尝试实现同样的目标,我会用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
Run Code Online (Sandbox Code Playgroud)
然后我想创建数据类,这样,当我运行 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
)
Run Code Online (Sandbox Code Playgroud)
但它总是在编写 ConstructorBinding 的两个地方抛出此异常
Kotlin:此注释不适用于目标“类”
springboot 3.0.0、java 18、kotlin 1.7.21
小智 7
我希望这有帮助
\n我现在不再使用@ConstructingBinding
\n这就是我的实现方式
应用程序.yaml
\nconference:\n plan-id: P1_1\n product-id: product1\nRun Code Online (Sandbox Code Playgroud)\n会议.kt
\nimport org.springframework.boot.context.properties.ConfigurationProperties\n\n@ConfigurationProperties(prefix = "conference")\ndata class Conferences(\n val planId: String,\n val productId: String,\n)\nRun Code Online (Sandbox Code Playgroud)\n用法.kt
\nobject MySample {\n fun haveFun(conference : Conference) : String {\n return conference.planId\n } \n}\n\n@Component\nclass BootLoader(val conference: Conference) : CommandLineRunner {\n override fun run(vararg args: String?) {\n println(MySample.haveFun(conference))\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n供参考
\n“类型级别不再需要 @ConstructingBinding”\n“改进了 @ConstructorBinding 检测 当使用构造函数绑定 @ConfigurationProperties 时,如果类具有单个参数化构造函数,则不再需要 @ConstructorBinding 注释。如果您有多个构造函数,则您将不再需要 @ConstructorBinding 注释。 \xe2\x80\x99ll 仍然需要使用 @ConstructorBinding 来告诉 Spring Boot 使用哪一个。"\n"对于大多数用户来说,这一更新的逻辑将允许使用更简单的 @ConfigurationProperties 类。但是,如果您有一个 @ConfigurationProperties 并且如果您想将 bean 注入构造函数而不是绑定它,您\xe2\x80\x99现在需要添加 @Autowired 注释。”
\n参考
\n https://github.com/spring-projects/spring-boot
@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
)
Run Code Online (Sandbox Code Playgroud)
主类中需要@ConfigurationPropertiesScan注释
| 归档时间: |
|
| 查看次数: |
4575 次 |
| 最近记录: |