這個問題整整折騰了我兩天,如今記錄下來,但願能夠幫助和我同樣,遇到相同問題的小夥伴。java
項目是分層的(Intellij IDEA中的模塊Module),有API(Core)層,Service&Dao,Common,Model,上一張項目結構圖。(不要在乎爲何Service和Dao放在一塊兒。這不是重點。)spring
API中包括了Controller,Mongodb在Service&Dao層中,也就是API層,調用Service&Dao層,我敢用性命擔保,全部註釋,邏輯,都沒有錯,可是運行SpringBoot的時候,恰恰報錯。(找不到依賴,就是注入失敗。)sql
代碼中繼承了MongoRepository接口mongodb
public interface IUserGroupRepository extends MongoRepository<UserGroup, Integer> { UserGroup findById(Integer id); }
報錯內容以下:express
2017-06-28 10:11:52.423 WARN 8648 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userGroupController': Unsatisfied dependency expressed through field 'userGroupRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.iboxpay.nosql.mongodb.IUserGroupRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 2017-06-28 10:11:52.426 INFO 8648 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2017-06-28 10:11:52.446 INFO 8648 --- [ main] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2017-06-28 10:11:52.591 ERROR 8648 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Field userGroupRepository in com.iboxpay.ops.api.controller.UserGroupController required a bean of type 'com.iboxpay.nosql.mongodb.IUserGroupRepository' that could not be found. Action: Consider defining a bean of type 'com.iboxpay.nosql.mongodb.IUserGroupRepository' in your configuration.
解決辦法以下:apache
@SpringBootApplication(scanBasePackages = {"com.iboxpay.service", "com.iboxpay.ops.api", "com.iboxpay.nosql"}) @EnableMongoRepositories(basePackages = {"com.iboxpay.nosql"}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
由於個人項目是分層的,SpringBoot的@SpringBootApplication註解要添加掃描包,不然有的地方可能會注入失敗。另一點比較重要,須要使有和Mongodb的@EnableMongoRepositories註解,並指定要掃描的包(IUserGroupRepository所在的包,即繼承api
MongoRepository接口的接口中所在的包。)
上面兩個com.iboxpay.nosql缺一不可。切記,切記。