简体   繁体   中英

How to autowire a generic bean in spring

How to autowire a generic bean in spring?

I have a dao implement as follows:

@Transactional
public class GenericDaoImpl<T> implements IGenericDao<T>
{

    private Class<T> entityClass;

    @Autowired
    private SessionFactory sessionFactory;

    public GenericDaoImpl(Class<T> clazz) {

        this.entityClass = clazz;
    }
    ...
}

Now I want to autowired the DaoImpl like this:

@Autowired
GenericDaoImpl<XXXEntity> xxxEntityDao;

I config in the spring xml:

<bean id="xxxEntityDao" class="XXX.GenericDaoImpl">
    <constructor-arg name="clazz">
        <value>xxx.dao.model.xxxEntity</value>
    </constructor-arg>
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

But I doesn't work, How should I config it? or a good practice about generic Dao implement?

Work with your interfaces instead of implementations

Do not use @Transactional in your persistent layer as it is much more likely that it belongs to your service layer.

Those being said, it might make more sense to extend the generic dao and autowire that. An example would be something like :

public interface UserDao extends GenericDao<User> {

    User getUsersByNameAndSurname(String name, String surname);
    ... // More business related methods
}

public class UserDaoImpl implements UserDao {

    User getUsersByNameAndSurname(String name, String surname);
    {
        ... // Implementations of methods beyond the capabilities of a generic dao
    }

    ...
}

@Autowired
private UserDao userDao; // Now use directly the dao you need

But if you really really want to use it that way you have to declare a qualifier :

@Autowired
@Qualifier("MyBean")
private ClassWithGeneric<MyBean> autowirable;

There is an alternative way.

I change the GenericDaoImpl<T> to a common class without Generic but use the generic in function level, and the entityClass can be configured in spring xml.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM