Java 抽象类的自动连线依赖项注入失败
我正在使用Spring3和Hibernate4 我的班级结构如下Java 抽象类的自动连线依赖项注入失败,java,spring,hibernate,abstract-class,Java,Spring,Hibernate,Abstract Class,我正在使用Spring3和Hibernate4 我的班级结构如下 public interface GenericDAO<T> { public void create(T entity); public void update(T entity); public void delete(T entity); } 我面临的问题是,当我尝试部署时,会出现以下异常。 如果我从EmployeeDAOImpl中删除abstract,并从EmployeeDAO中删除
public interface GenericDAO<T> {
public void create(T entity);
public void update(T entity);
public void delete(T entity);
}
我面临的问题是,当我尝试部署时,会出现以下异常。
如果我从EmployeeDAOImpl
中删除abstract
,并从EmployeeDAO
中删除extends GenericDAO
,则应用程序部署时不会出错。因此,不可能为EmployeeDAOImpl
创建抽象的类,或者我需要在没有抽象的情况下在DAO实现中实现泛型DAO
的所有方法
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
通用DAOImpl
public class GenericDAOImpl<T> implements GenericDAO<T> {
public void create(T entity) {
}
public void update(T entity) {
}
public void delete(T entity) {
}
public类GenericDAOImpl实现GenericDAO{
公共无效创建(T实体){
}
公共无效更新(T实体){
}
公共作废删除(T实体){
}
员工激励计划
public class EmployeeDAOImpl extends GenericDAOImpl<Employee> implements EmployeeDAO {
公共类EmployeeDAOImpl扩展了GenericDAOImpl实现EmployeeDAO{
确认以下标记中的spring上下文xml中是否提到EmployeeDAOImpl或其他带注释的类包。除非这样做,否则注释将不会被读取,也不会被初始化
<context:component-scan base-package="com.app.service" />
为什么要将类实现声明为抽象的?从概念上讲,这是一个矛盾。显然Spring无法实例化它,并且失败了。Java(因此Spring)无法创建抽象类的实例:在Java允许您创建实例之前,每个方法都必须有一个实现,否则在尝试调用该方法时会出现运行时错误。您需要删除“abstract”从EmployeeDao导入并实现从GenericDAO继承的方法。是,它在applicationContext.xml中执行包扫描您无法创建实例(bean)对于抽象类,它在java规范中。Createabstract-GenericDAOImpl通过实现实现GenericDAO
,并从GenericDAOImpl
继承EmployeeDAOImpl
@user1516873方法,如findeemployee
特定于Employee
实体,而EmployeeDAO
是在GenericDAOImpl
中包含这一点是个好主意。我通常会在GenericDAO中添加一些CRUD方法,比如findById、findAll、removeById。除此之外的所有内容都在特定于域对象的iface/impl中。在您的情况下findeemployee
肯定应该在EmployeeDAO
中,而不是在GenericDAO
@user1516873 s中o您的意思是说创建、更新和删除应该特定于实体或域?CRUD操作很常见,可以在泛型类中移动。因此它是特定于域的。当然,如果需要,您可以在特定于实体的dao中重写它。Stephen那么,将EmployeeDAOImpl中的所有泛型dao方法实现为创建更新和删除是一种最佳实践吗delete是所有DAO类的常用方法,属于泛型类型。有各种各样的模式,没有一种是特别好的解决方案。在Java 8中,您可以定义接口的默认实现(类似于mixin)这将使这更容易。同时,您可以创建一个抽象的GenericDOAImpl,提供CRUD的默认实现,然后让EntityDAOImpl扩展GenericDOAImpl。Stephen我已经修改了我的EmployeeDAOImpl
和GenericDOAImpl
,如我在问题中提到的编辑1,请看一看。谢谢
public class EmployeeDAOImpl extends GenericDAOImpl<Employee> implements EmployeeDAO {
<context:component-scan base-package="com.app.service" />