天天看點

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

繼續閱讀