Remove @Repository
annotation from AbstractGenericDAO
and make it abstract
:
public abstract class AbstractGenericDAO<T extends Serializable, ID extends Serializable>
implements GenericDAO<T, ID>
Your problem occurs because @Repository
is a specialization of @Component
, which means that Spring will try to create AbstractGenericDAO
instances for injection. Since AbstractGenericDAO
superclass (Object
) is not generic, you will not be able to downcast its Type
to ParameterizedType
, and so this line of code will fail (in the same way that it would if you tried to instantiate it manually with new AbstractGenericDAO()
):
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
The specialized class ShlkActiveWorkflowDAOImpl
should still be annotated with @Repository
. When spring tries to create a instance of this class a implicit call to AbstractGenericDAO
constructor will occur, but this time the line of code mentioned above will run as expected. This happens because getClass()
returns ShlkActiveWorkflowDAOImpl.class
which is a subclass of the generic AbstractGenericDAO
(so the downcast to ParameterizedType
works).
Since ShlkActiveWorkflowDAOImpl
extends
AbstractGenericDAO<ShlkActiveWorkflow, Serializable>
the actual type ShlkActiveWorkflow
will be correctly reflected at runtime. This is a known workaround to avoid passing a Class<T>
reference to the AbstractGenericDAO
constructor.
If you are worried about the @Autowired
annotation at AbstractGenericDAO
, don't be. Spring will correctly wire everything up when you inject a instance of one of its subclasses.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…