關於SpringBoot bean無法注入的問題(與檔案包位置有關)

gefangshuai發表於2015-12-16

問題場景描述

整個專案通過Maven構建,大致結構如下:

  • 核心Spring框架一個module spring-boot-base
  • service和dao一個module server-core
  • 提供系統後臺資料管理一個module server-platform-app
  • 給移動端提供rest資料介面一個module server-mobile-api

Paste_Image.png
其中server-platform-appserver-mobile-api分別是兩個springboot搭建的獨立服務端。server-platform-app大致業務開發接近尾聲,然後獨立出另一個web端server-mobile-api用於給mobile端提供資料。可就在搭建完成之後遇到了奇葩問題!

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [io.github.gefangshuai.rtat.service.RestaurantService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
    ... 24 more

總是提示無法注入Service或者Dao中的Bean!

解決分析

後來經研究發現,SpringBoot專案的Bean裝配預設規則是根據Application類所在的包位置從上往下掃描!
“Application類”是指SpringBoot專案入口類。這個類的位置很關鍵:

如果Application類所在的包為:io.github.gefangshuai.app,則只會掃描io.github.gefangshuai.app包及其所有子包,如果service或dao所在包不在io.github.gefangshuai.app及其子包下,則不會被掃描!

知道這一點非常關鍵,不知道Spring文件裡有沒有給出說明,如果不知道還真是無從解決。

相關文章