[英]Spring Annotations: Why @Required doesn't work when class is @Autowired
[英]Why Spring @Autowired doesn't work in abstract class?
我在抽象 class 中這樣做
@Autowired
lateinit var fileContract: FileContract
有錯誤
kotlin.UninitializedPropertyAccessException: lateinit property fileContract has not been initialized
但同樣適用於常規 class。 為什么?
您應該盡可能使用構造函數注入而不是字段注入。 這也可以解決您的問題,因為您不需要在抽象 class 中自動裝配任何內容,但您只需將其聲明為構造函數參數:
abstract class AbstractExtractor(
val fileContract: FileContract,
val dictionaryContractImpl: DictionaryContractImpl,
val regulationContractImpl: RegulationContractImpl
) {
...
}
請注意,上述符號將fileContract
、 dictionaryContractImpl
和regulationContractImpl
聲明為構造函數參數,同時(由於val
關鍵字)作為 class AbstractExtractor
的本地屬性。 這意味着無需在 class 中為它們聲明任何其他變量。
現在,您的子類RegulationExtractor
還需要使用構造函數注入,以便它可以將自動裝配的值傳遞給超級 class 的構造函數:
@Service
class RegulationExtractor(
fileContract: FileContract,
dictionaryContractImpl: DictionaryContractImpl,
regulationContractImpl: RegulationContractImpl
) : AbstractExtractor(
fileContract,
dictionaryContractImpl,
regulationContractImpl
) {
...
}
如果您還需要RegulationExtractor
class 中的任何構造函數參數,您可以像在AbstractExtractor
中一樣添加val
關鍵字。
此處應該不需要添加@Autowired
注解,但如果需要,可以將上面的代碼更改為
@Service
class RegulationExtractor @Autowired constructor(
...
您是否嘗試將@Component
注釋添加到具有未初始化字段的抽象 class 中? 我們遇到了類似的問題,它為我們解決了問題。
因為您無法為抽象 class 創建實例/bean。 它是“抽象的” 。
你不能有一個實例/bean,所以你不能將任何東西連接到實例。 而已。
我相信你會得到類似“沒有定義唯一的 bean”。 如果你這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.