Spring Boot 调用 MongoRepository时报org.springframework.beans.factory.NoSuchBeanDefinitionException错误的解决

这个问题整整折腾了我两天,如今记录下来,但愿能够帮助和我同样,遇到相同问题的小伙伴。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缺一不可。切记,切记。
相关文章
相关标签/搜索