注入失败,因为找不到bean

时间:2019-06-20 10:45:52

标签: spring spring-boot spring-mvc spring-data-jpa

我正在尝试使用Spring Boot使用controller-service-dao-entity体系结构开发非常简单的基本RESTful Web服务,但是我的应用程序无法启动,因为在服务级别注入dao类失败因为找不到dao类bean。

在这里您可以看到我的dao类,该类具有@Repository批注,据我了解,对于Spring Boot来说,创建Bean足够了。

package daoClasses;

import entityClasses.Tabella;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface TabellaDao extends JpaRepository<Tabella, Integer> {

}

我尝试使用@Autowired批注注入服务级别的控制器类

package controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import services.TabellaService;

@RestController
@RequestMapping("/api")
public class TabellaController {

    @Autowired
    public TabellaService tabellaService;

    @GetMapping("/tabella")
    public String getNomeTabella(){

        return tabellaService.findTabellaById().getNome();
    }
}

和我得到的错误。

***************************
APPLICATION FAILED TO START
***************************

Description:

Field tabellaDao in services.TabellaService required a bean of type 'daoClasses.TabellaDao' 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 'daoClasses.TabellaDao' in your configuration.


Process finished with exit code 0

在这里您可以看到我的应用程序类,在其中启动spring boot并指定要扫描的软件包。

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

@SpringBootApplication(scanBasePackages = {"controllers", "services", 
"daoClasses", "entityClasses"})
public class Application {

    public static void main(String[] args){

        SpringApplication.run(Application.class, args);
    }
}

如果仅将“ controllers”软件包作为scanBasePackages的参数,则会收到一个不同的错误,表示失败的注入是控制器级别的服务bean的注入,我认为这很自然,因为如果不要指定服务类所在的包,那么spring boot无法创建其bean。

但是您可以看到,即使我告诉Spring Boot扫描项目中的所有软件包,Spring Boot也无法创建dao类bean。

您知道什么可能导致此错误吗?

0 个答案:

没有答案
相关问题