spring boot jpa 工程出现Field XXX in XXX required a bean of type XXX that could not be found

一、序言

今天起床,继续敲打代码,于是,在一个点被绊了一下,于是就进行整理记录,本项目是采用springboot + jpa,对项目结构进行了分层,以下就是我项目结构,由于我在单项目结构并未遇到这样的情况与配置,所以我估计主要还是因为项目分层的原因
在这里插入图片描述

二、问题描述

项目问题从我在Controller中采用@Autowired进行自动注入时,idea却给了我这样的提示(这个提示截图不了,所以就进行了拍照)
在这里插入图片描述
idea居然提示我不能自动注入,说没有这个bean,我心想,会不会idea出问题了,因为以前idea也提示我dao接口不能注入,于是,我没有理会,就启动了项目,然后控制台就果真报了,这样的错误,我就很疑惑了,单体应用时,这样的做法没什么不可,到了这里怎么就注入失败了呢

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

Description:

Field userService in com.dely.web.controller.web.controller.sys.UserController required a bean of type 'com.dely.system.service.sys.UserService' 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.dely.system.service.sys.UserService' in your configuration.

三、问题的解决

在进行查阅资料是,一个注解@ComponentScan,让我恍然大悟,明白了应该就是扫描的问题了,由于类根本不在同一个项目中,所以需要进行包扫描的配置,最终,需要设置的包扫描注解如下

@ComponentScan

@ComponentScan用来扫描和发现指定包及其子包中的被@Component(@Service、@Controller)定义。其用法如下:

@ComponentScan(basePackages = {"com.dely.system.service.*", "com.dely.web.controller.*"})

@EntityScan

@EntityScan用来扫描和发现指定包及其子包中的Entity定义。其用法如下:

@EntityScan(basePackages = {"com.dely.system.entity.*"})

@EnableJpaRepositories

@EnableJpaRepositories用来扫描和发现指定包及其子包中的Repository定义。其用法如下:

@EnableJpaRepositories(basePackages = {"com.dely.system.dao.*"})

最终,我对启动配置类,增加了以上注解,项目就得以启动成功

/**
 * dele-admin 启动入口
 * @author ruiMin
 */
@SpringBootApplication
@ComponentScan(basePackages = {"com.dely.system.service.*", "com.dely.web.controller.*", "com.dely.common.*"})
@EntityScan(basePackages = {"com.dely.system.entity.*"})
@EnableJpaRepositories(basePackages = {"com.dely.system.dao.*"})
public class WebApplication {

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

}

发布了40 篇原创文章 · 获赞 11 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Chen_RuiMin/article/details/104291623