Spring Boot 調用 MongoRepository時報org.springframework.beans.factory.NoSuchBeanDefinitionException錯誤的解決辦法


這個問題整整折騰了我兩天,現在記錄下來,希望可以幫助和我一樣,遇到相同問題的小伙伴。

項目是分層的(Intellij IDEA中的模塊Module),有API(Core)層,Service&Dao,Common,Model,上一張項目結構圖。(不要在意為什么Service和Dao放在一起。這不是重點。)

API中包括了Controller,Mongodb在Service&Dao層中,也就是API層,調用Service&Dao層,我敢用性命擔保,所有注釋,邏輯,都沒有錯,但是運行SpringBoot的時候,偏偏報錯。(找不到依賴,就是注入失敗。)

代碼中繼承了MongoRepository接口

public interface IUserGroupRepository extends MongoRepository<UserGroup, Integer> {
    UserGroup findById(Integer id);
}

 報錯內容如下:

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.

  解決辦法如下:

@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所在的包,即繼承

MongoRepository接口的接口中所在的包。)
上面兩個com.iboxpay.nosql缺一不可。切記,切記。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM