could not found bean for MongoRepository (Spring Boot)

我的梦境 提交于 2019-12-21 04:17:21

问题


I am using spring boot and MongoDB.

Spring version : 4.3.9

Spring boot version : 1.5.4

I am creating a repository which implements MongoRepository interface, like below

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface HotelRepository extends MongoRepository<Hotel,String> {
}

But, whenever I am adding a dependency to HotelRepository compiler giving the error Field hotelRepository in com.demo.HotelController required a bean of type 'com.demo.HotelRepository' that could not be found.

@RestController
@RequestMapping("/hotel")
public class HotelController {

    @Autowired
    private HotelRepository hotelRepository;

    @GetMapping("/all")
    public List<Hotel> getAllHotels(){
        return this.hotelRepository.findAll();
    }
}

I've examine all the aspects from my side to resolve the error but all in vain. What I've R&D.

  • For HotelRepository there will be a default implementation provided out of the box. as per spring docs
  • I've annotated the interface with @Repository, so no need to put @Component
  • Adding dependency from spring context using @Autowired annotation, So it should pick created bean from spring context.
  • All the required files are in the same package, so no need to put @ComponentScan

Here is my main spring boot application class :

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MongoWithBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MongoWithBootApplication.class, args);
    }
}

application.properties :

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=HotelDB

Stack trace :

2017-07-10 13:25:12.485  INFO 4712 --- [           main] com.demo.MongoWithBootApplication        : Starting MongoWithBootApplication on KELLGGNCPU0313 with PID 4712 (D:\STS_WS\MongoWithBoot\target\classes started by mehrajuddin.malik in D:\STS_WS\MongoWithBoot)
2017-07-10 13:25:12.487  INFO 4712 --- [           main] com.demo.MongoWithBootApplication        : No active profile set, falling back to default profiles: default
2017-07-10 13:25:12.519  INFO 4712 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@13acb0d1: startup date [Mon Jul 10 13:25:12 IST 2017]; root of context hierarchy
2017-07-10 13:25:13.448  INFO 4712 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-07-10 13:25:13.456  INFO 4712 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-07-10 13:25:13.456  INFO 4712 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-07-10 13:25:13.541  INFO 4712 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-07-10 13:25:13.541  INFO 4712 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1025 ms
2017-07-10 13:25:13.635  INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-07-10 13:25:13.637  INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-10 13:25:13.638  INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-07-10 13:25:13.638  INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-07-10 13:25:13.638  INFO 4712 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-07-10 13:25:13.673  WARN 4712 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hotelController': Unsatisfied dependency expressed through field 'hotelRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.demo.HotelRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-07-10 13:25:13.675  INFO 4712 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-07-10 13:25:13.684  INFO 4712 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-07-10 13:25:13.737 ERROR 4712 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field hotelRepository in com.demo.HotelController required a bean of type 'com.demo.HotelRepository' that could not be found.


Action:

Consider defining a bean of type 'com.demo.HotelRepository' in your configuration.

pom.xml :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>MongoWithBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>MongoWithBoot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Could someone please help me out here what am I missing?


回答1:


Faced similar problem, Adding the following to Application class helped me resolving the problem

@EnableMongoRepositories(basePackageClasses = DeviceDataRepository.class)

In your case it could be

@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = HotelRepository.class)
public class MongoWithBootApplication{ ... }



回答2:


I was facing the same problem

Used below code to scan mongorepository packages

@SpringBootApplication                                                       
@EnableMongoRepositories(basePackages = {"//packages you want to scan for activiting mongo repositories"})
public class SpringBootMongoDBApp{ ... }

It resolved my problem




回答3:


we need to activate mongo repositories using EnableMongoRepositories

@SpringBootApplication
@EnableMongoRepositories //specify packages to scan
public class MongoWithBootApplication{ ... }



回答4:


After so much of struggle, finally I've resolved the problem.

There is nothing wrong in the code or annotation. The problem was spring boot's version.

However, I am still not sure what is the wrong in the version above 1.5.1.RELEASE .If anybody knows the root cause can edit or answer the question.

Problem : If I add spring-boot-starter-parent above 1.5.1.RELEASE, it gives me the above no bean error for MongoRepository. It gives error from 1.5.2 to 1.5.4 version. (1.5.4 was the last version till that I've tried and faced the no bean error)

Solution : It runs fine if I add spring-boot-starter-parent 1.5.1.RELEASE or below (1.5.0 was lowest version till I've tried).




回答5:


I have the same structure and I just had to add this configuration:

Application.java

@Configuration
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    ...
}

application.properties

spring.data.mongodb.uri=mongodb://localhost:27017/hotelDB

And the repository package have to be in a deeper level of Application.java class. Thats all

com.hotelDB
    Application.java
    repository (Package)
    controller (Package)
    service (Package)
    ...



回答6:


Just tried and did not found any problem at all with my existing spring boot mongodb project with 1.5.4.RELEASE for spring-boot-starter-parent.

Earlier it was configured with 1.4.0.RELEASE.



来源:https://stackoverflow.com/questions/45006266/could-not-found-bean-for-mongorepository-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!