Spring嵌套的ConfigurationProperties和Kotlin

时间:2019-09-04 07:25:32

标签: spring spring-boot kotlin

我想在Spring Boot中使用嵌套的ConfigurationProperties,它在Java中可用,但在Kotlin中不可用。我的应用属性中包含以下几行:

cert.signing-cert.filePath=truststore.jks
cert.signing-cert.password=xxxx
cert.private-signing.filePath=sign_test.p12
cert.private-signing.password=xxxx
cert.private-encrpytion.filePath=encryption_test.p12
cert.private-encrpytion.password=xxx

我创建了这个结构来处理这些属性:

@Component
@ConfigurationProperties("cert")
class CertConfig {
    lateinit var signingCert: SigningCert
    lateinit var privateSigning: PrivateSigning
    lateinit var privateEncrpytion: PrivateEncrpytion

    class SigningCert {
        lateinit var filePath: String
        lateinit var password: String
    }

    class PrivateSigning {
        lateinit var filePath: String
        lateinit var password: String
    }

    class PrivateEncrpytion {
        lateinit var filePath: String
        lateinit var password: String
    }
}

我添加了kapt插件并对其build.gradle.kts产生了依赖性

    kotlin("kapt") version "1.3.50"
...
    kapt("org.springframework.boot:spring-boot-configuration-processor")
    implementation("org.springframework.boot:spring-boot-configuration-processor")

运行此代码时,我得到了这个异常:

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property signingCert has not been initialized

1 个答案:

答案 0 :(得分:2)

我忘了初始化属性。

 var signingCert: SigningCert = SigningCert()
 var privateSigning: PrivateSigning = PrivateSigning()
 var privateEncrpytion: PrivateEncrpytion = PrivateEncrpytion()