[英]Use abstract class for instance variable in Spring
My issue is that I have a Spring model 我的问题是我有一个Spring模型
@Entity
public class PetOwner {
@ManyToOne
@JoinColumn(name = "pet_id", nullable = true)
private Pet pet;
with Pet being an abstract class with 2 subclasses Dog and Cat. 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
When I create a new PetOwner in a Struts-form and try to bind its pet to either a Dog or Cat object, I get an error on submitting the form: 当我以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
How can I tell Spring to initialize the de.model.Dog or de.model.Cat based on the class pet-object? 如何告诉Spring根据类pet-object初始化de.model.Dog或de.model.Cat?
FYI: I have a PetDAO and PetService, but I am not sure whether they influence this problem. 仅供参考:我有PetDAO和PetService,但我不确定它们是否会影响这个问题。
I appreciate every help! 我感谢每一个帮助!
Personally, I would turn Pet
to an Interface
and make Cat
and Dog
implement it to avoid this kind of problems. 就个人而言,我会将
Pet
变成一个Interface
,让Cat
和Dog
实现它以避免这种问题。 Sorry for off-topic! 对不起题!
Anyhow, if you want some member of your class to be dynamically initialized\\populated, try the Lookup Method Injection. 无论如何,如果你想要动态初始化/填充你的类的某个成员,请尝试查找方法注入。 Read pp. 3.3.4.1 here .
阅读第3.3.4.1 这里 。
If the class that contains the dynamic member was created in scope=singletone (the default for spring bean container) every time you will access the field that has a lookup method assigned, you will get an appropriate object according to the business logic implemented inside the lookup method. 如果包含动态成员的类是在scope = singletone(spring bean容器的缺省值)中创建的,每次访问分配了查找方法的字段时,您将根据在其中实现的业务逻辑获得适当的对象。查找方法。
Also, I found this example in Spring documentation - I think it is very clear. 另外,我在Spring文档中找到了这个例子 - 我认为它非常清楚。 Take a look at "3.4.6.1 Lookup method injection"
看看“3.4.6.1 Lookup方法注入”
When you configure the PetOwner
class assign a lookup method to its Pet
member - it will be called whenever you need a new instance of the Pet bean. 配置
PetOwner
类时,为其Pet
成员分配查找方法 - 只要您需要Pet bean的新实例,就会调用它。
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.