Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vcredit.lrh.db.mongodb; import com.mongodb.Mongo; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import static java.util.Collections.singletonList; /** * * @author Liu Jianwei<liujianwei@vcredit.com> * @date 2016-5-13 */ @EnableConfigurationProperties({ LRHMongoProperties.class }) public class LRHMongoConfiguration extends AbstractMongoConfiguration { @Autowired private LRHMongoProperties mongoProperties; @Override protected String getDatabaseName() { return mongoProperties.getDatabase(); } @Override public Mongo mongo() throws Exception { if (mongoProperties.getUsername() != null && mongoProperties.getPassword() != null) { return new MongoClient( singletonList(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort())), singletonList(MongoCredential.createCredential(mongoProperties.getUsername(), mongoProperties.getDatabase(), mongoProperties.getPassword().toCharArray()))); } else { return new MongoClient( singletonList(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort()))); } } }