mongodb 找不到MongoRepository的Bean(Sping Boot )

14ifxucb  于 2023-03-01  发布在  Go
关注(0)|答案(7)|浏览(274)

我使用的是spring bootMongoDB

Spring version : 4.3.9

Spring boot version : 1.5.4

我正在创建一个实现MongoRepositoryinterface的存储库,如下所示

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

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

但是,每当我向HotelRepository编译器添加依赖项时,就会出现错误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();
    }
}

我已经从我这边检查了所有的方面来解决这个错误,但是都是徒劳的。

  • 对于HotelRepository,将提供开箱即用的默认实现。as per spring docs
  • 我已经用@Repository注解了接口,所以不需要把@Component
  • 使用@Autowired注解从Spring上下文添加依赖项,因此它应该从Spring上下文中选择创建的bean。
  • 所有需要的文件都在同一个包中,因此不需要放置@ComponentScan

下面是我的主要Spring Boot应用程序类:

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);
    }
}
    • 应用程序。属性:**
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=HotelDB
    • 堆栈跟踪**:
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>

有没有人能帮我弄清楚我错过了什么?

q9yhzks0

q9yhzks01#

面对类似的问题,添加以下应用程序类帮助我解决了这个问题

@EnableMongoRepositories(basePackageClasses = DeviceDataRepository.class)

对你来说可能是

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

slhcrj9b2#

我也面临着同样的问题
使用以下代码扫描mongorepository包

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

它解决了我的问题

hvvq6cgz

hvvq6cgz3#

我们需要使用EnableMongoRepositories激活mongo存储库

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

dwbf0jvd4#

我有相同的结构,只需要添加以下配置:
Application.java

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

application.properties

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

并且存储库包必须位于www.example.com类的更深层次Application.java。

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

wvmv3b1j5#

经过这么多的努力,我终于解决了这个问题.
代码或注解中没有错误。问题出在spring boot的版本上
不过我还是不确定1.5.1.RELEASE以上的版本到底出了什么问题,如果有人知道根本原因可以编辑或者回答这个问题。

    • 问题**:如果我在1.5.1.RELEASE上添加spring-boot-starter-parent,它会给我上面的MongoRepository的no bean错误。它会给1.5.21.5.4版本的错误。(1.5.4是最后一个版本,直到我尝试并面对no bean错误)
    • 溶液**:如果我添加spring-boot-starter-parent1.5.1.RELEASE或更低版本(1.5.0是我尝试过的最低版本),它运行良好。
sirbozc5

sirbozc56#

刚刚尝试,并没有发现任何问题,在所有与我现有的Spring Boot mongodb项目与1.5.4.RELEASEspring-boot-starter-parent
之前它是用1.4.0.RELEASE配置的。

ct3nt3jp

ct3nt3jp7#

以下作品:

@EnableJpaRepositories(basePackages = {"com.company.machine.repository", "com.company.system.repository"})
@EnableMongoRepositories(basePackages = {"com.company.system.repository", "com.company.machine.repository"})

相关问题