Use abstract class for instance variable in Spring

My problem is I have a Spring model

@Entity
public class PetOwner {
    @ManyToOne
    @JoinColumn(name = "pet_id", nullable = true)
    private Pet pet;

      

when Pet is an abstract class with two 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 Struts form and try to bind its pet to a Dog or Cat object, I get an error:

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 de.model.Dog or de.model.Cat based on the class of the pet object?

FYI: I have PetDAO and PetService, but I'm not sure if they affect this problem.

I appreciate any help!

+3


source to share


1 answer


Personally, I would convert Pet

to Interface

and do Cat

and Dog

implement it to avoid problems like this. Sorry for the off-topic!

Anyway, if you want any member of your class to be dynamically initialized / populated then try the lookup method lookup. Read p. 3.3.4.1 here .

If a class containing a dynamic element was created in scope = singleletone (default for a spring bean container) every time you access a field that has a lookup method, you will get the corresponding object according to your business logic. implemented inside the search method.



Also, I found this example in the spring documentation - I think it is very clear. Take a look at "3.4.6.1 Finding Injection Method"

When setting up a class, PetOwner

assign a lookup method to its member Pet

- it will be called whenever you need a new Pet bean instance.

Good luck!

+1


source







All Articles