[英]Use abstract class for instance variable in Spring
我的問題是我有一個Spring模型
@Entity
public class PetOwner {
@ManyToOne
@JoinColumn(name = "pet_id", nullable = true)
private Pet pet;
Pet是一個抽象類,有2個子類Dog和Cat。
@Entity
@Inheritance(strategy= InheritanceType.JOINED)
public abstract class Pet {
@OneToMany(fetch = FetchType.LAZY)
protected Set<PetOwner> owners;
}
@Entity
public class Cat extends Pet
@Entity
public class Dog extends Pet
當我以Struts形式創建一個新的PetOwner並嘗試將其寵物綁定到Dog或Cat對象時,我在提交表單時收到錯誤:
Error creating bean with name 'de.model.Pet': Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Could not instantiate bean class [de.model.Pet]: Is it an abstract class?;
nested exception is java.lang.InstantiationException
如何告訴Spring根據類pet-object初始化de.model.Dog或de.model.Cat?
僅供參考:我有PetDAO和PetService,但我不確定它們是否會影響這個問題。
我感謝每一個幫助!
就個人而言,我會將Pet
變成一個Interface
,讓Cat
和Dog
實現它以避免這種問題。 對不起題!
無論如何,如果你想要動態初始化/填充你的類的某個成員,請嘗試查找方法注入。 閱讀第3.3.4.1 這里 。
如果包含動態成員的類是在scope = singletone(spring bean容器的缺省值)中創建的,每次訪問分配了查找方法的字段時,您將根據在其中實現的業務邏輯獲得適當的對象。查找方法。
另外,我在Spring文檔中找到了這個例子 - 我認為它非常清楚。 看看“3.4.6.1 Lookup方法注入”
配置PetOwner
類時,為其Pet
成員分配查找方法 - 只要您需要Pet bean的新實例,就會調用它。
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.