Connect to remote MongoDB database using Java web application. Below code surely help you.
Before to use below code please add property file having credentials all other required details in it. Read that property file in spring-config.xml. You can use below code to read the property 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;
}
172.234.52.24:8888?
8888
isn't the default port. docs.mongodb.org/manual/tutorial/… – Plat