title: com.mongodb.MongoSocketReadException: Prematurely reached end of stream
body: <p>I am using remote MongoDB and connecting that with my Spring boot application. Application works fine if I define <em>spring.data.mongodb.uri</em> in my <strong>application.properties</strong> file, along with username and password.
  Something similar to </p>
  
  <pre><code>spring.data.mongodb.uri = mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
  </code></pre>
  
  <p>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. </p>
  
  <p>I tried to create MongoDBTemplate in <strong>Configuration</strong> class, but it is throwing </p>
  
  <blockquote>
    <p>com.mongodb.MongoSocketReadException: Prematurely reached end of
    stream</p>
  </blockquote>
  
  <p>Here's the code</p>
  
  <pre><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);
  
      }
  
  }
  </code></pre>