在我开始之前,请假定pom.xml
是完美的。
话虽如此,我们还是继续吧,
我得到的错误如下:
申请启动失败* 字段empDao in com.sagarp.employee.EmployeeService 需要一个无法找到的'com.sagarp.employee.EmployeeDao‘类型的bean。
现在,spring boot application
类如下所示:
package com.sagarp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableEurekaClient //this is for eureka which not our concern right now.
@ComponentScan(basePackages = "com.sagarp.*") //Included all packages
public class EmployeeHibernateApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeHibernateApplication.class, args);
}
}
EmployeeService
类如下所示:
package com.sagarp.employee;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmployeeService {
@Autowired
private EmployeeDao empDao; // interface
public EmployeeDao getEmpDao() {
return empDao;
}
public void setEmpDao(EmployeeDao empDao) {
this.empDao = empDao;
}
//some methods
}
请注意,
EmployeeDao
是一个接口。
EmployeeDao
接口如下:
public interface EmployeeDao {
//Oh! so many methods to I have provided
}
类,它实现了EmployeeDaoImpl
接口。
public class EmployeeDaoImpl implements EmployeeDao {
@Autowired
private SessionFactory sessionFactory;
//Oh!So many methods I had to implement
}
我想,由于EmployeeService
与@Service
连接的原因,它是自动定位的。我在components
中添加了所有包,这样它就可以扫描和实例化我可能拥有的所有依赖项。
但事实并非如此,因此问题就来了。
有人能帮我解决以上细节的错误吗?如果需要更多的细节,请告诉我。
发布于 2018-07-18 05:41:41
EmployeeDaoImpl
没有注册为bean。有两种方法: XML或注释。既然您已经使用了注释,那么您就可以这样做:
@Repository
public class EmployeeDaoImpl implements EmployeeDao {
@Autowired
private SessionFactory sessionFactory;
//...
}
注意,您已经将EmployeeService
注册为@Service
的bean。在此之后,应该在容器中识别bean并进行适当的注入。
为什么@Repository
是DAO,而不是@Service
呢?怎么决定?有关更多信息,请阅读白龙氏病文章。
@Component
是任何Spring托管组件的通用原型@Service
在服务层对类进行注释@Repository
在持久化层对类进行注释,该类将充当数据库存储库。发布于 2018-07-18 05:41:28
组件扫描搜索带有Spring原型注释的类。为了使一个类符合自动配线的条件,它必须有以下注释之一。
解决方案是用@Component、@Service或@Repository对EmployeeDaoImpl进行注释。
发布于 2018-07-18 05:42:04
还应该对EmployeeDaoImpl进行注释。
@Repository
public class EmployeeDaoImpl implements EmployeeDao {
@Autowired
private SessionFactory sessionFactory;
//Oh!So many methods I had to implement
}
这应该能解决这个问题。
https://stackoverflow.com/questions/51403415
复制