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都掃描注入進來。如果不加`@ComponentScanspring-boot默認只會加載當前工程的所有Bean。如果有多個文件包,則:

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章