我正在嘗試data class使用 Spring Boot 在 Kotlin 中進行配置。我有以下課程:
@Configuration
@ConfigurationProperties(prefix = "spring.braintree")
data class BraintreeConfigProperties(
val merchantId: String = "",
val publicKey: String = "",
val privateKey: String = "",
val environment: Environment = Environment.SANDBOX
)
以及以下屬性:
spring.braintree.merchantId=${BRAINTREE_MERCHANT_ID}
spring.braintree.publicKey=${BRAINTREE_PUBLIC_KEY}
spring.braintree.privateKey=${BRAINTREE_PRIVATE_KEY}
當我運行應用程式時,出現以下例外:
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'spring.braintree' to com.x.ps.config.BraintreeConfigProperties$$EnhancerBySpringCGLIB$$311e0531:
Property: spring.braintree.merchant-id
Value: ${BRAINTREE_MERCHANT_ID}
Origin: class path resource [application.properties] - 5:29
Reason: java.lang.IllegalStateException: No setter found for property: merchant-id
Action:
Update your application's configuration
但是,我也有一個與班級完全相同的BraintreeConfigProperties班級。這個類 ( DatabaseConfigProperties) 確實有效。它們完全相同。
我試過的:
- 檢查屬性名稱是否與配置名稱實際匹配。
- 分別嘗試了所有三個配置屬性。
- 將值為 1234 的非環境變數附加到 MercerId 屬性,這會導致以下例外:
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'spring.braintree' to com.x.ps.config.BraintreeConfigProperties$$EnhancerBySpringCGLIB$$62509e61:
Property: spring.braintree.merchant-id
Value: 1234
Origin: class path resource [application.properties] - 5:29
Reason: java.lang.IllegalStateException: No setter found for property: merchant-id
Action:
Update your application's configuration
uj5u.com熱心網友回復:
這里的問題val是最終的并且var可以更改。因此,您應該將屬性更改為var.
更多資訊:https ://medium.com/mindorks/kotlin-series-val-vs-var-difference-android-kotlin-ecad780daeb7
uj5u.com熱心網友回復:
Kotlin 僅在將欄位宣告為val. 然而,Spring 使用 setter 將屬性中的值注入到物件中。
使用較新版本的 Spring Boot,您可以通過建構式而不是使用 setter 來注入值,從而將data classes 與欄位一起使用。val
您可以通過使用來做到這一點,請參閱官方檔案@ConstructorBinding中的以下示例:
@ConstructorBinding
@ConfigurationProperties("example.kotlin")
data class KotlinExampleProperties(
val name: String,
val description: String,
val myService: MyService) {
data class MyService(
val apiToken: String,
val uri: URI
)
}
使用 lateinit var 或初始化為 null 的 var 也可以。很可能您不想在初始化后更改這些欄位,因此val在大多數情況下似乎更適合,而不是在后臺宣告 avar并生成一個 setter。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426030.html
