我正在使用 Java 和 Kotlin 開發一個專案。該專案最初僅在 java 中。我正在將一些類遷移到 kotlin。但是我在遷移到 kotlin 的課程中??遇到了這個問題。此問題在組態檔中。
組態檔。
package com.fourtwenty.core
import ...
class CoreModule : AbstractModule() {
override fun configure() {
// Repositories
bind(AppRepository::class.java).to(AppRepositoryImpl::class.java)
...
// Services
bind(AuthenticationService::class.java).to(AuthenticationServiceImpl::class.java)
BindingClassImpl
package com.fourtwenty.core.services.mgmt.impl
import ...
open class AuthenticationServiceImpl @Inject constructor(token: Provider<ConnectAuthToken>) : AbstractAuthServiceImpl(token), AuthenticationService {
@Inject
private val metrcAccountRepository: MetrcAccountRepository? = null
@Inject
private val stripeService: StripeService? = null
@Inject
var integrationSettingRepository: IntegrationSettingRepository? = null
@Inject
private val shopPaymentOptionRepository: ShopPaymentOptionRepository? = null
@Inject
private val amazonServiceManager: AmazonServiceManager? = null
...
系結類
package com.fourtwenty.core.services.mgmt
import ...
interface AuthenticationService {
fun getCurrentActiveEmployee(): InitialLoginResult?
fun adminLogin(request: EmailLoginRequest?): InitialLoginResult?
...
我在 IntellIJ 中遇到了這個錯誤
1) Injected field com.fourtwenty.core.services.mgmt.impl.AuthenticationServiceImpl.metrcAccountRepository cannot be final.
at com.fourtwenty.core.CoreModule.configure(CoreModule.kt:1266)
2) Injected field com.fourtwenty.core.services.mgmt.impl.AuthenticationServiceImpl.stripeService cannot be final.
at com.fourtwenty.core.CoreModule.configure(CoreModule.kt:1266)
3) Injected field com.fourtwenty.core.services.mgmt.impl.AuthenticationServiceImpl.shopPaymentOptionRepository cannot be final.
at com.fourtwenty.core.CoreModule.configure(CoreModule.kt:1266)
4) Injected field com.fourtwenty.core.services.mgmt.impl.AuthenticationServiceImpl.amazonServiceManager cannot be final.
at com.fourtwenty.core.CoreModule.configure(CoreModule.kt:1266)
5) ...
uj5u.com熱心網友回復:
我從未使用過 Guice(我假設這是 guice,因為它沒有被標記),但是與 spring 出現了相同的問題,因此應該應用相同的解決方案。
這些欄位val在初始化為 null 后不能被 DI 框架修改。
他們將需要成為var,以便之后可以更新。
最重要的是,您可能確定大多數或所有這些欄位不會為空,因此可以使用 lateinit 關鍵字來規避冗長的可空性檢查。事實上,DI 是提到存在 lateinit 關鍵字的主要用例之一:https ://kotlinlang.org/docs/properties.html#late-initialized-properties-and-variables
所以它會變成:
private lateinit var metrcAccountRepository: MetrcAccountRepository
請注意val,如果可能,在您的情況下,更清潔的替代方案(使用 )是進行建構式注入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/462663.html
