字段中需要一个无法找到的类型的 bean 考虑在您的配置中定义一个类型的 bean

Field in required a bean of type that could not be found consider defining a bean of type in your configuration

我在尝试 运行 我的应用程序时遇到以下错误:

Field edao in com.alon.service.EmployeeServiceImpl required a bean of type 'com.alon.repository.EmployeeRepository' that could not be found.

The injection point has the following annotations:

  • @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'com.alon.repository.EmployeeRepository' in your configuration.

项目结构:

员工资料库:

package com.alon.repository;

import com.alon.model.Employee;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface EmployeeRepository {
    List<Employee> findByDesignation(String designation);
    void saveAll(List<Employee> employees);
    Iterable<Employee> findAll();
}

EmployeeServiceImpl:

package com.alon.service;

import com.alon.model.Employee;
import com.alon.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeRepository edao;

    @Override
    public void saveEmployee(List<Employee> employees) {
        edao.saveAll(employees);
    }

    @Override
    public Iterable<Employee> findAllEmployees() {
        return edao.findAll();
    }

    @Override
    public List<Employee> findByDesignation(String designation) {
        return edao.findByDesignation(designation);
    }
}

我的申请:

package com.alon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplicataion {
    public static void main(String[] args) {
        SpringApplication.run(MyApplicataion.class, args);
    }
}

由于您添加了 spring-boot 标签,我猜您正在使用 sprig data jpa。您的存储库接口应扩展 org.springframework.data.repository.Repository(标记接口)或其子接口之一(通常为 org.springframework.data.repository.CrudRepository)以指示 spring 提供存储库的运行时实现(如果有任何这些接口)没有延长你会得到

bean of type 'com.alon.repository.EmployeeRepository' that could not be found.

我假设您尝试使用 spring 数据 JPA。您可以检查/调试的是:

  • JpaRepositoriesAutoConfiguration执行了吗?你可以在调试日志级别的启动日志中看到这个
  • 如果您另外添加 @EnableJpaRepositories 和相应的基础包,会有什么变化吗?
  • @ComponentScan添加到相应的包中,通常@SpringBootApplication应该这样做,但以防万一。

您还可以查看自动配置文档:https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html

编辑:请参阅@ali4j 的评论:我没有看到它是通用的 spring 存储库接口而不是 spring 数据接口

问候,WiPu