天天看点

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

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都扫描注入进来。如果不加

`@ComponentScan

spring-boot默认只会加载当前工程的所有Bean。如果有多个文件包,则:

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

继续阅读