在 spring boot 中自动装配时无法找到特定类型的 bean

Unable to find bean of certain type while autowiring in springboot

在我开始之前,请假设 pom.xml 没有故障。

话虽如此,让我们继续,

我收到的错误如下:

APPLICATION FAILED TO START *************************** Description:

Field empDao in com.sagarp.employee.EmployeeService required a bean of type 'com.sagarp.employee.EmployeeDao' that could not be found.

现在spring boot applicationclass如下:

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);
    }
}

EmployeeServiceclass如下:

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
}

Please note that EmployeeDao is an interface.

EmployeeDao界面如下:

public interface EmployeeDao {
    //Oh! so many methods to I have provided
}

EmployeeDaoImpl class 实现了 EmployeeDao 接口。

public class EmployeeDaoImpl implements EmployeeDao {

    @Autowired
    private SessionFactory sessionFactory;

    //Oh!So many methods I had to implement
}

我想由于 EmployeeService@Service 注释的原因,它是自动自动装配的。 我在 components 中添加了所有包,以便它扫描并实例化我可能拥有的所有依赖项。

但是没有,所以才有问题。

任何人都可以帮助我解决上述详细信息的错误。 如果需要更多详细信息,请告诉我。

组件扫描搜索 类 带有 Spring 刻板印象注释的注释。为了使 class 符合自动装配的条件,它必须具有这些注释之一。

解决方案是使用@Component、@Service 或@Repository 注释EmployeeDaoImpl。

EmployeeDaoImpl 未注册为 bean。有两种方式:XML或者注解。既然你已经使用了注解,那么你开始吧:

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

    @Autowired
    private SessionFactory sessionFactory;

    //...
}

请注意,您已经将 EmployeeService 注册为 @Service 的 bean。在此之后,bean 应该在容器中被识别并正确注入。

为什么 @Repository 用于 DAO 而不是 @Service?如何决定?阅读 Baeldung's 文章了解更多信息。

  • @Component 是任何 Spring 托管组件的通用构造型
  • @Service在服务层注释类
  • @Repository在持久层注解类,将充当数据库存储库

EmployeeDaoImpl 也应该被注解。

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

   @Autowired
   private SessionFactory sessionFactory;

   //Oh!So many methods I had to implement
}

这应该可以解决问题。