为抽象类注入自动连接的依赖项失败

时间:2013-03-07 11:06:21

标签: java spring hibernate abstract-class

我正在使用Spring 3和Hibernate 4

我有以下类结构

public interface GenericDAO<T> {

    public void create(T entity);
    public void update(T entity);
    public void delete(T entity);
}

DAO课程

public interface EmployeeDAO extends GenericDAO<Employee>  {

    public void findEmployee(EmployeeQueryData data);
}

DAO实施课程

@Repository("employeeDAO")
public abstract class EmployeeDAOImpl implements EmployeeDAO {

protected EntityManager entityManager;

@Override
public void findEmployee(EmployeeQueryData data) {

...... code

}

我面临的问题是当我尝试部署时,我遇到以下异常。 如果我从abstract删除EmployeeDAOImpl并从extends GenericDAO<Employee>删除EmployeeDAO,则会部署应用程序而不会出现错误。因此,abstract不能使用EmployeeDAOImpl课程,或者我需要在没有GenericDAO的DAO实施中实施abstract的所有方法?

Error creating bean with 
name 'employeeService': Injection of autowired dependencies failed; \
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: test.dao.EmployeeDAO 
test.service.EmployeeServiceImpl.employeeDAO; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No matching bean of type [test.dao.EmployeeDAO] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for 
this dependency. Dependency annotations: 
{@javax.inject.Inject()}.

修改1

GenericDAOImpl

public class GenericDAOImpl<T> implements GenericDAO<T> {    

    public void create(T entity) {
    }       
    public void update(T entity) {
    }
    public void delete(T entity) {
    }

EmployeeDAOImpl

public class EmployeeDAOImpl extends GenericDAOImpl<Employee> implements EmployeeDAO {

3 个答案:

答案 0 :(得分:3)

Java(以及Spring)无法创建抽象类的实例:在Java允许您创建实例之前,每个方法都必须具有实现,否则在尝试调用该方法时会出现运行时错误。您需要从EmployeeDAOImpl中删除“abstract”并实现从GenericDAO继承的方法。

答案 1 :(得分:2)

为什么要将类实现声明为抽象?从概念上讲,这是一个矛盾。显然Spring无法实例化它并失败。

答案 2 :(得分:1)

确认以下标记中的spring context xml中是否提及了EmployeeDAOImpl或其他带注释的类包。除非这样做,否则注释将不会被读取,也不会被初始化。

<context:component-scan base-package="com.app.service" />