Spring Boot 以及如何配置到 MongoDB 的连接详细信息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23515295/
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 06:42:44  来源:igfitidea点击:

Spring Boot and how to configure connection details to MongoDB?

springmongodbspring-dataspring-boot

提问by Marco

Being new to Spring Boot I am wondering on how I can configure connection details for MongoDB. I have tried the normal examples but none covers the connection details.

作为 Spring Boot 的新手,我想知道如何为 MongoDB 配置连接详细信息。我已经尝试了正常的例子,但没有一个涵盖连接细节。

I want to specify the database that is going to be used and the url/port of the host that runs MongoDB.

我想指定将要使用的数据库以及运行 MongoDB 的主机的 url/端口。

Any hints or tips?

任何提示或提示?

回答by Artem Bilan

Just to quote Boot Docs:

只是引用引导文档

You can set spring.data.mongodb.uriproperty to change the url, or alternatively specify a host/port. For example, you might declare the following in your application.properties:

您可以设置spring.data.mongodb.uri属性来更改 url,或者指定一个host/port. 例如,您可以在您的application.properties:

spring.data.mongodb.host=mongoserver
spring.data.mongodb.port=27017

All available options for spring.data.mongodbprefix are fields of MongoProperties:

spring.data.mongodb前缀的所有可用选项都是以下字段MongoProperties

private String host;

private int port = DBPort.PORT;

private String uri = "mongodb://localhost/test";

private String database;

private String gridFsDatabase;

private String username;

private char[] password;

回答by Ali Dehghani

spring.data.mongodb.hostand spring.data.mongodb.portare not supported if you're using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.urishould be used to provide all of the configuration, like this:

spring.data.mongodb.hostspring.data.mongodb.port如果您使用的是Mongo 3.0 Java 驱动程序,则不受支持。在这种情况下,spring.data.mongodb.uri应该使用提供所有的配置,像这样:

spring.data.mongodb.uri=mongodb://user:[email protected]:12345

回答by asmaier

In a maven project create a file src/main/resources/application.ymlwith the following content:

在 maven 项目中创建一个src/main/resources/application.yml包含以下内容的文件:

spring.profiles: integration
# use local or embedded mongodb at localhost:27017
---
spring.profiles: production
spring.data.mongodb.uri: mongodb://<user>:<passwd>@<host>:<port>/<dbname>

Spring Boot will automatically use this file to configure your application. Then you can start your spring boot application either with the integration profile (and use your local MongoDB)

Spring Boot 将自动使用此文件来配置您的应用程序。然后您可以使用集成配置文件(并使用您的本地 MongoDB)启动您的 Spring Boot 应用程序

java -jar -Dspring.profiles.active=integration your-app.jar

or with the production profile (and use your production MongoDB)

或使用生产配置文件(并使用您的生产 MongoDB)

java -jar -Dspring.profiles.active=production your-app.jar

回答by Mari Murotani

You can define more details by extending AbstractMongoConfiguration.

您可以通过扩展 AbstractMongoConfiguration 来定义更多细节。

@Configuration
@EnableMongoRepositories("demo.mongo.model")
public class SpringMongoConfig extends AbstractMongoConfiguration {
    @Value("${spring.profiles.active}")
    private String profileActive;

    @Value("${spring.application.name}")
    private String proAppName;

    @Value("${spring.data.mongodb.host}")
    private String mongoHost;

    @Value("${spring.data.mongodb.port}")
    private String mongoPort;

    @Value("${spring.data.mongodb.database}")
    private String mongoDB;

    @Override
    public MongoMappingContext mongoMappingContext()
        throws ClassNotFoundException {
        // TODO Auto-generated method stub
        return super.mongoMappingContext();
    }
    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient(mongoHost + ":" + mongoPort);
    }
    @Override
    protected String getDatabaseName() {
        // TODO Auto-generated method stub
        return mongoDB;
    }
}

回答by Danilo Teodoro

It's also important to note that MongoDB has the concept of "authentication database", which can be different than the database you are connecting to. For example, if you use the official Docker image for Mongoand specify the environment variables MONGO_INITDB_ROOT_USERNAMEand MONGO_INITDB_ROOT_PASSWORD, a user will be created on 'admin' database, which is probably not the database you want to use. In this case, you should specify parameters accordingly on your application.propertiesfile using:

同样重要的是要注意 MongoDB 具有“身份验证数据库”的概念,它可能与您要连接的数据库不同。例如,如果您使用Mongo官方 Docker 映像并指定环境变量 MONGO_INITDB_ROOT_USERNAMEMONGO_INITDB_ROOT_PASSWORD,则会在“ admin”数据库上创建一个用户,这可能不是您要使用的数据库。在这种情况下,您应该使用以下命令在application.properties文件中相应地指定参数:

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=<username specified on MONGO_INITDB_ROOT_USERNAME>
spring.data.mongodb.password=<password specified on MONGO_INITDB_ROOT_PASSWORD>
spring.data.mongodb.database=<the db you want to use>

回答by Sanjay-Dev

Here is How you can do in Spring Boot 2.0by creating custom MongoClient adding Providing more control for Connection ,

以下是如何在Spring Boot 2.0 中通过创建自定义 MongoClient 添加为 Connection 提供更多控制,

Please follow github Link for Full Source Code

请按照 github 链接获取完整源代码

@Configuration
@EnableMongoRepositories(basePackages = { "com.frugalis.repository" })
@ComponentScan(basePackages = { "com.frugalis.*" })
@PropertySource("classpath:application.properties")
public class MongoJPAConfig extends AbstractMongoConfiguration {

    @Value("${com.frugalis.mongo.database}")
    private String database;
    @Value("${com.frugalis.mongo.server}")
    private String host;
    @Value("${com.frugalis.mongo.port}")
    private String port;
    @Value("${com.frugalis.mongo.username}")
    private String username;
    @Value("${com.frugalis.mongo.password}")
    private String password;


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

    @Override
    protected String getMappingBasePackage() {
        return "com.frugalis.entity.mongo";
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoClient(), getDatabaseName());
    }

    @Override
    @Bean
    public MongoClient mongoClient() {

        List<MongoCredential> allCred = new ArrayList<MongoCredential>();
        System.out.println("???????????????????"+username+" "+database+" "+password+" "+host+" "+port);
        allCred.add(MongoCredential.createCredential(username, database, password.toCharArray()));
        MongoClient client = new MongoClient((new ServerAddress(host, Integer.parseInt(port))), allCred);
        client.setWriteConcern(WriteConcern.ACKNOWLEDGED);

        return client;
    }}