【问题标题】:Field in required a bean of type that could not be found consider defining a bean of type in your configuration字段中需要一个找不到类型的 bean 考虑在您的配置中定义一个类型的 bean
【发布时间】:2019-07-01 09:51:49
【问题描述】:

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

com.alon.service.EmployeeServiceImpl 中的字段 edao 需要一个 bean 键入找不到的“com.alon.repository.EmployeeRepository”。

注入点有如下注解:

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

行动:

考虑定义一个 bean 类型 'com.alon.repository.EmployeeRepository' 在您的配置中。

项目结构:

EmployeeRepository:

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

【问题讨论】:

  • 如果没有实现,EmployeeRepository 将不可用。创建一个实现。

标签: java spring spring-boot spring-data-elasticsearch


【解决方案1】:

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

“com.alon.repository.EmployeeRepository”类型的 bean 不能 找到了。

【讨论】:

    【解决方案2】:

    我假设您尝试使用 Spring Data JPA。您可以检查/调试的是:

    • JpaRepositoriesAutoConfiguration 被执行了吗?您可以在调试日志级别的启动日志中看到这一点
    • 如果您在相应的基础包中额外添加@EnableJpaRepositories,是否会有所改变。
    • 将@ComponentScan与相应的包一起添加,通常@SpringBootApplication应该这样做,但以防万一。

    您也可以查看 autconfig 文档:https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html

    编辑:查看@ali4j 的评论:我没有看到它是通用的spring Repository 接口而不是spring 数据接口

    问候,维普

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 2021-11-25
      • 2021-05-30
      • 2017-05-30
      • 2020-08-01
      • 2019-02-14
      • 2018-12-21
      相关资源
      最近更新 更多