Connect to a remote MongoDB database using a Java web application. Below code will definitely help you.
Before using the code below, add a properties file that has credentials, all other necessary data. Read this properties file in spring -config.xml. You can use the code below to read the properties file -
<context:property-placeholder location='classpath:/config/configTest.properties'/>
@Configuration Public class MongoConfiguration extends AbstractMongoConfiguration {
@Value("${mongodb.dbname}") private String dbName; @Value("${mongodb.host}") private String host; @Value("${mongodb.port}") private Integer port; @Value("${mongodb.username}") private String userName; @Value("${mongodb.password}") private String password; @Value("${mongodb.authenticationdatabase}") private String authenticationDatabase; @Override protected String getDatabaseName() { return this.dbName; } @Override public MongoClient mongo() throws Exception { List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); ServerAddress address = new ServerAddress(host, port); serverAddresses.add(address); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); MongoCredential credential = MongoCredential.createPlainCredential(userName, authenticationDatabase, password.toCharArray()); credentials.add(credential); return new MongoClient(serverAddresses, credentials); } @Override @Bean public SimpleMongoDbFactory mongoDbFactory() throws Exception { return new SimpleMongoDbFactory(mongo(), getDatabaseName()); } @Override @Bean public MongoTemplate mongoTemplate() throws Exception { final MongoTemplate mongoTemplate = new MongoTemplate(mongo(), getDatabaseName()); mongoTemplate.setWriteConcern(WriteConcern.SAFE); return mongoTemplate; }
source share