欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring-boot 引用子项目的service或则dao时,运行报错:NoSuchBeanDefinitionException

程序员文章站 2022-04-30 20:00:12
...

spring-boot 引用子项目的service或则dao时,运行报错:NoSuchBeanDefinitionException,如下:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.jx.ekoochak.common.service.SysUserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 28 more

 

背景介绍:项目在存在子父模块时,当前子模块在启动是时会加载当前项目上下文的Bean,不会去查找子工程中定义的一些model,service,dao等方法bena。所以在运行时会无法在容器中查找到对应的引用Bean。

解决方法:在当前子项目启动中,显示的注入父模块Bean,如果当前工程引用了多个,可以注入多个包路径,如下:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
​
@SpringBootApplication
@ComponentScan("com.jx.ekoochak")
@MapperScan("com.jx.ekoochak.common.mapper")
public class EkoochakMerchantApplication {
    public static void main(String[] args) {
        SpringApplication.run(EkoochakMerchantApplication.class, args);
    }
}

@ComponentScan("com.jx.ekoochak")我的项目文件包都是以com.jx.ekoochak开头,所以把此路径下的bean都扫描注入进来。如果不加`@ComponentScanspring-boot默认只会加载当前工程的所有Bean。如果有多个文件包,则:

@ComponentScan({"com.in28minutes.springboot.basics.springbootin10steps","com.in28minutes.springboot.somethingelse"})