Kotlin读取springboot配置文件yml中的map

看了这么多,没一个能用的,反而是gpt帮我解决了问题。

1. yml

url:
  node:
    80001: "https://url-1"
    11155111: "https://url-2"

2. NodeUrlProperties.kt

import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component

@Component
@ConfigurationProperties("url")
class NodeUrlProperties {
    lateinit var node: Map<Long, String>
}

3. 读取Map的数值

@Component
class YourClass() {
    @Autowired
    private lateinit var nodeUrlProperties: NodeUrlProperties

    fun chooseNodeAddress(chainId: Long): Result<String?> {
        return runCatching {
            nodeUrlProperties.node[chainId]
        }
    }
}

就是这么简单,希望能帮到大家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Kotlin 创建 Spring Boot配置 properties 类可以按照以下步骤进行: 1. 创建一个 Kotlin 类,例如 `MyProperties.kt`。 2. 在类上添加 `@ConfigurationProperties` 注解,并指定 prefix(前缀)。例如,如果你想要配置的属性前缀是 `myapp`,那么注解应该如下所示: ``` @ConfigurationProperties(prefix = "myapp") class MyProperties { // properties } ``` 3. 在类添加与配置属性对应的变量,并为它们添加 `@Value` 注解。例如,如果你想要配置一个字符串类型的属性 `name`,那么代码应该如下所示: ``` @ConfigurationProperties(prefix = "myapp") class MyProperties { @Value("\${myapp.name}") lateinit var name: String } ``` 注意,这里使用了 `lateinit` 来延迟初始化,因为在构造函数无法为这些变量赋值。 4. 在 Spring Boot 应用程序的配置添加 `@EnableConfigurationProperties` 注解,并将 `MyProperties` 类作为参数传递进去。例如,如果你的配置类名为 `MyAppConfig`,那么代码应该如下所示: ``` @Configuration @EnableConfigurationProperties(MyProperties::class) class MyAppConfig { // other configurations } ``` 现在你就可以在其他组件注入 `MyProperties` 类,并使用其的属性了。例如,你可以在一个服务类注入 `MyProperties` 类,并在其使用 `name` 属性,例如: ``` @Service class MyService(private val myProperties: MyProperties) { fun getName(): String { return myProperties.name } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值