0

如何在春季自动装配通用 bean?

我有一个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;
    }
    ...
}

现在我想像这样自动装配 DaoImpl:

@Autowired
GenericDaoImpl<XXXEntity> xxxEntityDao;

我在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>

但是我不工作,我应该如何配置它?还是关于通用 Dao 实现的好习惯?

4

2 回答 2

1

使用您的接口而不是实现

不要在持久层中使用@Transactional,因为它更有可能属于您的服务层。

话虽如此,扩展通用 dao 并自动装配它可能更有意义。一个例子是这样的:

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

但是,如果您真的真的想以这种方式使用它,则必须声明一个限定符:

@Autowired
@Qualifier("MyBean")
private ClassWithGeneric<MyBean> autowirable;
于 2014-10-23T13:45:45.327 回答
0

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.

于 2014-10-24T11:33:22.537 回答