如何在Dao层继承?

时间:2015-11-12 10:31:11

标签: spring

我正在使用SpringMVC + Hibernate,我想在DAO层中应用继承,我的做法如下:

BaseDao.java

public interface BaseDao
{
   public Serializable save(Object object) throws DataAccessException,
        HibernateException;

public void merge(Object object) throws DataAccessException,
        HibernateException;

public void flush() throws DataAccessException,HibernateException;
 }

EmpDao.java

 public interface EmpDao extends BaseDao{
 }

BaseDaoImpl.java

@Repository
public class BaseDaoImpl implements BaseDao{
 // Implementation for baseDao methods 
}

EmpDaoImpl .java

 @Repository
public class EmpDaoImpl extends BaseDaoImpl implements EmpDao{
 // Implementation
}

但我收到以下错误:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 
[BaseDao] is defined: expected single matching bean but found 2

我在这里缺少什么?

4 个答案:

答案 0 :(得分:1)

If you really want to have both BaseDaoImpl and EmpDaoImpl as two beans in your Spring container, you need to tell Spring which one to use wherever you have an @Autowired field of type BaseDao using @Qualifier annotation.

Related: Understanding Spring @Autowired usage

答案 1 :(得分:0)

你需要在@NoRepositoryBean界面上添加BaseDao,这样春天就不会为它创建一个bean,也不会为EmpDao我假设

答案 2 :(得分:0)

您似乎正在尝试注入BaseDao而Spring正在抱怨有两位候选人。

我认为这实际上是一个设计问题。您希望将BaseDaoImpl用作直接使用的具体bean,也可以用作其他DAO的基类。这很糟糕,因为子类实际上并没有扩展,而只是使用他们的父类。更好的模式是摆脱extends并简单地将BaseDaoImpl注入其他DAO。

此外,界面看起来多余。如果您正在解决代理问题,请使用proxyTargetClass

答案 3 :(得分:0)

您可以使用像这样的通用类型

<强> BaseDao.java

public interface BaseDao<EntityType extends Object>
{
   public Serializable save(EntityType entity) throws DataAccessException,
        HibernateException;

   public void merge(EntityType entity) throws DataAccessException,
        HibernateException;

   public void flush() throws DataAccessException,HibernateException;
}

<强> BaseDaoImpl.java

@Repository
public abstract class BaseDaoImpl<EntityType extends Object> implements BaseDao<EntityType>{
 // Implementation for baseDao methods 
}

<强> EmpDao.java

 public interface EmpDao extends BaseDao<Employee>{
 }

EmpDaoImpl .java

 @Repository
public class EmpDaoImpl extends BaseDaoImpl<Employee> implements EmpDao{
 // Implementation
}