You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中通过@Value注解读取多Spring Profile配置文件?

解决方案

首先修正配置文件错误

你的application-prod.yml中spring.profiles的值写错了,应该改为prod,否则Spring无法正确识别这个生产环境配置文件:

spring.profiles: prod 

key:
- name: lisa
  roles:
    - doctor
    - nurse
    - patient

核心问题说明

Spring同时激活多个Profile时,后激活的Profile属性会覆盖前面的同名属性(你这里prod在test之后,所以最终key只会保留prod的内容)。要同时获取两个文件的key属性,必须通过区分属性名或分Profile绑定的方式实现。


方案1:给不同Profile的属性加前缀(推荐)

修改两个配置文件,为key添加环境专属前缀,避免属性覆盖:

application-test.yml

spring.profiles: test 

test-key:
- name: tom
  roles:
    - student
    - teacher
    - friend

application-prod.yml

spring.profiles: prod 

prod-key:
- name: lisa
  roles:
    - doctor
    - nurse
    - patient

然后通过@ConfigurationProperties绑定属性(比@Value更适合复杂结构):

  1. 定义对应配置结构的数据类:
data class Person(
    val name: String,
    val roles: List<String>
)
  1. 编写配置类,分Profile绑定并获取属性:
@Configuration
@Profile(value = ["test", "prod"])
class MessageConfig {

    // 绑定test环境的属性
    @Bean
    @ConfigurationProperties(prefix = "test-key")
    @Profile("test")
    fun testPersons(): List<Person> = mutableListOf()

    // 绑定prod环境的属性
    @Bean
    @ConfigurationProperties(prefix = "prod-key")
    @Profile("prod")
    fun prodPersons(): List<Person> = mutableListOf()

    // 输出两个环境的属性内容
    @Bean
    fun readMessage(testPersons: List<Person>, prodPersons: List<Person>) {
        println("Test环境的key属性: $testPersons")
        println("Prod环境的key属性: $prodPersons")
    }
}

方案2:分Profile单独绑定(不修改属性名)

如果不想修改原属性名,可以针对每个Profile单独创建配置类:

  1. 定义数据类:
data class Person(
    val name: String,
    val roles: List<String>
)
  1. 为test环境创建配置类:
@Configuration
@Profile("test")
@ConfigurationProperties(prefix = "key")
class TestConfig {
    lateinit var persons: List<Person>
}
  1. 为prod环境创建配置类:
@Configuration
@Profile("prod")
@ConfigurationProperties(prefix = "key")
class ProdConfig {
    lateinit var persons: List<Person>
}
  1. 在主配置类中注入并使用:
@Configuration
@Profile(value = ["test", "prod"])
class MessageConfig(
    private val testConfig: TestConfig,
    private val prodConfig: ProdConfig
) {
    @Bean
    fun readMessage() {
        println("Test环境的key属性: ${testConfig.persons}")
        println("Prod环境的key属性: ${prodConfig.persons}")
    }
}

关于@Value的说明

@Value仅适合注入简单类型属性(如字符串、数字),无法直接解析key这种复杂的列表嵌套结构,因此不推荐用它来获取你的key属性。

内容的提问来源于stack exchange,提问作者Kate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:40:38