user6332430
user6332430

Reputation: 460

Spring dependency injection not working with inheritance

I have a generic base dao class in which I implemented some generic methods for all daos.

<bean id="baseDAO" class="com.db.dao.BaseDao">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="userDAO" class="com.db.dao.UserDao"></bean>

<bean id="notesDAO" class="com.db.dao.NotesDao"></bean>

Initially, I was using the dependency injection to inject sessionFactory to every single dao, but later on I had implemented a base dao and had every other daos to extend this base dao.

However, after the change, whenever I call getSessionFactory() from one of the daos, I get null as return. The change makes sense to me but I cannot seem to figure out why it would return null since I've had the factorySession injected in the base.

BaseDao

public class BaseDao<T> {

    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
       this.sessionFactory = sessionFactory;
    }

    ...
}

UserDao

public class UserDao extends BaseDao<User> {

    public User read(String userName) {
        Session session = getSessionFactory().getCurrentSession();
        session.beginTransaction();
        ...
    }

    ...
}

Upvotes: 4

Views: 679

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

The way i see it is that you forgot to add parent attribute on the children:

<bean id="baseDAO" class="com.db.dao.BaseDao" abstract="true">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="userDAO" class="com.db.dao.UserDao" parent="baseDAO"></bean>

<bean id="notesDAO" class="com.db.dao.NotesDao" parent="baseDAO"></bean>

I think its also a good idea if you mark the BaseDAO as abstract.

Upvotes: 5

Related Questions