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缺一不可。切记,切记。
原文地址:https://www.cnblogs.com/zhuiyi/p/7088558.html