在springboot中自动装配时找不到特定类型的bean

时间:2018-07-18 13:34:38

标签: java spring spring-boot autowired

在我开始之前,请假设pom.xml没问题。

话虽如此,让我们继续

我得到的错误如下:

  

申请无法开始   ***************************说明:

     com.sagarp.employee.EmployeeService中的

字段empDao需要   键入找不到的“ com.sagarp.employee.EmployeeDao” 。

现在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类,它实现了EmployeeDao接口。

public class EmployeeDaoImpl implements EmployeeDao {

    @Autowired
    private SessionFactory sessionFactory;

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

我猜是由于EmployeeService@Service取消注释的原因,它是自动自动连接的。 我在components中添加了所有软件包,以便它将扫描并实例化我可能具有的所有依赖关系。

但是没有,因此是问题。

有人可以通过上述详细信息帮助我解决错误。 请让我知道是否需要更多详细信息。

3 个答案:

答案 0 :(得分:1)

组件扫描搜索使用Spring构造型注释进行注释的类。为了使一个类有资格自动装配,它必须具有以下注释之一。

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

答案 1 :(得分:1)

EmployeeDaoImpl未注册为bean。有两种方法:XML或注释。由于您已经使用了注释,因此您可以:

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

    @Autowired
    private SessionFactory sessionFactory;

    //...
}

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

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

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

答案 2 :(得分:1)

EmployeeDaoImpl也应添加注释。

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

   @Autowired
   private SessionFactory sessionFactory;

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

这应该可以解决问题。

相关问题