简体   繁体   English

如何在春季自动接线通用bean

[英]How to autowire a generic bean in spring

How to autowire a generic bean in spring? 如何在春季自动接线通用bean?

I have a dao implement as follows: 我有一个dao工具,如下所示:

@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: 现在,我想像这样自动连接DaoImpl:

@Autowired
GenericDaoImpl<XXXEntity> xxxEntityDao;

I config in the spring xml: 我在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? 或关于通用Dao工具的良好实践?

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. 不要在持久层中使用@Transactional,因为它很可能属于您的服务层。

Those being said, it might make more sense to extend the generic dao and autowire that. 话虽这么说,扩展通用的dao和autowire可能更有意义。 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. 我将GenericDaoImpl<T>更改为一个没有Generic的通用类,但在功能级别使用了generic,并且可以在spring xml中配置entityClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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