gpt4 book ai didi

java - 在 Spring 中使用抽象类作为实例变量

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:02:29 25 4
gpt4 key购买 nike

我的问题是我有一个 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 并尝试将其宠物绑定(bind)到 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 根据类宠物对象初始化 de.model.Dog 或 de.model.Cat?

仅供引用:我有一个 PetDAO 和 PetService,但我不确定它们是否会影响这个问题。

感谢您的帮助!

最佳答案

就我个人而言,我会把 Pet 变成一个 Interface 并让 CatDog 实现它来避免这种情况种问题。抱歉跑题了!

无论如何,如果您希望类的某些成员被动态初始化\填充,请尝试查找方法注入(inject)。阅读第 3.3.4.1 页 here .

如果包含动态成员的类是在 scope=singletone(spring bean 容器的默认设置)中创建的,每次访问分配了查找方法的字段时,您将根据业务逻辑获得适当的对象在查找方法中实现。

此外,我发现了这个 example在 Spring 文档中 - 我认为它非常清楚。看看《3.4.6.1 Lookup方法注入(inject)》

当您配置 PetOwner 类时,为它的 Pet 成员分配一个查找方法 - 只要您需要 Pet bean 的新实例,它就会被调用。

祝你好运!

关于java - 在 Spring 中使用抽象类作为实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26980363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com