How to use Spring to connect to MongoDB which requires authentication

前端 未结 3 1848
遇见更好的自我
遇见更好的自我 2020-12-08 16:50

I am using the below Spring configuration in order to connect to mongoDB



        
3条回答
  •  没有蜡笔的小新
    2020-12-08 17:36

    To update @Lealem Admassu's answer for java config, in Mongo 3 they changed the API, and now it is recommended to use mongo's MongoCredentials instead of UserCredentials.

    Here there is a simple example of how to get a MongoClient: http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.mongo-3.authentication

    The next code can be done modular, but more or less this works for me (I needed a MongoTemplate):

    public MongoTemplate getMongoTemplate(String host, int port,
                                          String authenticationDB,
                                          String database,
                                          String user, char[] password)
            throws UnknownHostException {
        return new MongoTemplate(
                new SimpleMongoDbFactory(
                        new MongoClient(
                                new ServerAddress(host, port),
                                Collections.singletonList(
                                        MongoCredential.createCredential(
                                                user,
                                                authenticationDB,
                                                password
                                        )
                                )
                        ),
                        database
                )
        );
    }
    

提交回复
热议问题