Spring Boot 和 Spring Data REST 中的 MongoDB 配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25991395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:04:49  来源:igfitidea点击:

MongoDB configuration in Spring Boot and Spring Data REST

springmongodbspring-dataspring-bootspring-data-rest

提问by Sarath

I want to use MongoDB for the mongoDB with spring-boot and JPA.. I'm able to do with embedded H2 database. But I'm not sure what's going wrong using mongo-db. While running the application, I'm getting error that datasource is missing.

我想将 MongoDB 用于带有 spring-boot 和 JPA 的 mongoDB。我可以使用嵌入式 H2 数据库。但我不确定使用 mongo-db 出了什么问题。在运行应用程序时,我收到数据源丢失的错误。

@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = "com..........repo")
@EnableWebMvc
@Configuration
@ComponentScan
@Import({ SpringMongoConfig.class, RepositoryRestMvcConfiguration.class })
public class Bootstrap extends SpringBootServletInitializer {

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

   @Override
   protected SpringApplicationBuilder configure(
           SpringApplicationBuilder application) {
       return application.sources(Bootstrap.class);
   }
}

.

.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;

@Configuration
@EnableMongoRepositories(basePackages = "com.............repo")
@PropertySource(value = "classpath:mongo-config.properties")
public class SpringMongoConfig extends AbstractMongoConfiguration {

@Value("${MONGO_DB_HOST}")
private String MONGO_DB_HOST;

@Value("${MONGO_DB_PORT}")
private int MONGO_DB_PORT;

@Value("${DB}")
private String DB;

@Override
protected String getDatabaseName() {
    return DB;
}

@Bean
@Override
public Mongo mongo() throws Exception {
    return new MongoClient(MONGO_DB_HOST, MONGO_DB_PORT);
}

}

.

.


org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:293)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
     ..........................
     Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:509)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:290)
    ... 25 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
....................................
     Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
    ... 39 common frames omitted
     Caused by: org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.getDriverClassName(DataSourceProperties.java:93)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource(DataSourceAutoConfiguration.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

回答by M. Deinum

For starters use the framework Spring Boot will do autoconfiguration for the frameworks it detects. This includes Spring Data JPA and Spring Data Mongo. So you can remove the @Enableannotation for it.

对于初学者,使用框架 Spring Boot 会自动配置它检测到的框架。这包括 Spring Data JPA 和 Spring Data Mongo。所以你可以删除@Enable它的注释。

The same for Spring MVC and Spring Data Rest.

Spring MVC 和 Spring Data Rest 也是如此。

To allow Spring Boot to configure Spring Mongo add the following properties to your application.properties

要允许 Spring Boot 配置 Spring Mongo,请将以下属性添加到您的 application.properties

spring.data.mongodb.host= # the db host
spring.data.mongodb.port=27017 # the connection port (defaults to 27107)

or the

或者

spring.data.mongodb.uri=mongodb://localhost/test # connection URL

More on the Spring Boot Mongo support can be found in this sectionof the Spring Boot Reference Guide.

有关 Spring Boot Mongo 支持的更多信息,请参见Spring Boot 参考指南的这一部分

When not using an embedded datasource you have to specify which driver to use for this add the following property to your application.properties. This is also documented in this sectionof the Spring Boot Reference Guide.

当不使用嵌入式数据源时,您必须指定为此使用哪个驱动程序,将以下属性添加到您的application.properties. 这也记录在Spring Boot 参考指南的这一部分中。

spring.datasource.driverClassName=your.driver.class

spring.datasource.driverClassName=your.driver.class

I suggest moving your Bootstrapclass to a top level package and remove all not needed annotations and configuration files

我建议将您的Bootstrap课程移至顶级包并删除所有不需要的注释和配置文件

@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Bootstrap extends SpringBootServletInitializer {

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

   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
       return application.sources(Bootstrap.class);
   }
}

Should be enough to bootstrap your whole application including jpa, mongo and web support.

应该足以引导您的整个应用程序,包括 jpa、mongo 和 web 支持。

For a quite complete list I suggest Appendix Aof the Spring Boot Reference Guide.

对于一个非常完整的列表,我建议使用 Spring Boot 参考指南的附录 A。