找不到所需类型的bean的字段,请考虑在配置中定义类型的bean

时间:2019-07-01 09:51:49

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

尝试运行我的应用时出现以下错误:

  

com.alon.service.EmployeeServiceImpl中的字段edao需要一个Bean   找不到“ com.alon.repository.EmployeeRepository”类型。

     

注入点具有以下注释:

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

操作:

     

考虑定义一个类型的bean   配置中的“ com.alon.repository.EmployeeRepository”。

项目结构:

enter image description here

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

2 个答案:

答案 0 :(得分:1)

当您添加了spring-boot标签时,我想您正在使用小枝数据jpa。您的存储库接口应扩展org.springframework.data.repository.Repository(标记接口)或其子接口之一(通常为org.springframework.data.repository.CrudRepository),以指示spring提供存储库的运行时实现(如果未扩展这些接口的话)会得到

  类型为'com.alon.repository.EmployeeRepository'的

bean无法   被发现。

答案 1 :(得分:0)

我假设您尝试使用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数据接口

关于,WiPu