My issue is that I have a Spring model
@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.
@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:
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?
FYI: I have a PetDAO and PetService, but I am not sure whether they influence this problem.
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. 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 .
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.
Also, I found this example in Spring documentation - I think it is very clear. Take a look at "3.4.6.1 Lookup method injection"
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.
Good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.