I am using remote MongoDB and connecting that with my Spring boot application. Application works fine if I define spring.data.mongodb.uri in my application.properties file, along with username and password. Something similar to
spring.data.mongodb.uri = mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
I wanted to keep encoded url in my application.property file and then want to decode it before use. I am using MongoOperations to query mongoDB.
I tried to create MongoDBTemplate in Configuration class, but it is throwing
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
Here's the code
package com.expensemanagement.base;
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
@Configuration
public class AppConfig {
@Bean
public MongoTemplate mongoTemplate() throws Exception {
char[] password2 = "XXXX".toCharArray();
MongoCredential credential2 = MongoCredential.createCredential("XXXX", "MongoDB",password2);
MongoClient mongoClient = new MongoClient(new ServerAddress("XXX-XXX-XX-XX-XXX.mongodb.net",27017), Arrays.asList(credential2));
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, "MongoDB");
return new MongoTemplate(mongoDbFactory);
}
}