2

我有一个 Kotlin 数据类,我想从application.yml文件中读取属性。这是我的数据类:

@ConstructorBinding
@ConfigurationProperties("meanwhile.in.hell.myapp")
data class MyAppProperties(val serverId: String, val locationId: String)

然后我将它添加到我的配置类中:

@Configuration
@EnableConfigurationProperties(MyAppProperties::class)
open class MyAppConfiguration(private val properties: MyAppProperties) {

我使用 just 访问值properties.serverId并将对象传递给正在创建的其他 bean 的构造函数,例如这个:

open class MyAppClient(
    private val webClient: WebClient,
    private val properties: MyAppProperties
) : IMyAppClient {

但是,当我启动我的应用程序时,我收到一个错误,它没有尝试从 加载属性application.yml,而是尝试为构造函数参数查找 bean:

Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'meanwhile.in.hell.myapp-meanwhile.in.hell.myapp.MyAppProperties': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

Parameter 0 of constructor in meanwhile.in.hell.myapp.MyAppProperties required a bean of type 'java.lang.String' that could not be found.

我如何阻止我的应用程序认为这些参数是自动装配的?我知道在 Kotlin 中,这就是构造函数 Autowired bean 的样子(即,不需要注释),但是我在网上看到的所有关于如何读取application.yml属性的示例看起来都与我的数据类相同。

Spring-Boot v2.3.0.RELEASE Kotlin v1.3.72

4

1 回答 1

2

原来我错过了依赖

org.jetbrains.kotlin:kotlin-reflect

文档: https ://docs.spring.io/spring-boot/docs/2.2.1.RELEASE/reference/htmlsingle/#boot-features-kotlin-requirements

问题: https ://github.com/spring-projects/spring-boot/issues/19582

于 2020-07-09T09:36:52.240 回答