Search code examples
javamongodbmongo-java

Use properties to parameterize connection to Mongodb


I am trying to use Properties file to parameterize connection to Mongodb.

I have added this function:

public static Properties load(String filename) throws IOException, FileNotFoundException{
  Properties properties = new Properties();

  FileInputStream input = new FileInputStream(filename);
  try{
     properties.load(input);
     return properties;
  }
     finally{
     input.close();
  }

}

and use this code:

    String path = System.getProperty("user.dir") + "/config.properties";
    Properties prop = load(path);

    //System.out.println("key: "+ prop.getProperty("MONGO_HOST"));


    try {
//m = new Mongo(config.MONGO_HOST, config.MONGO_PORT);
    m = new Mongo(prop.getProperty("MONGO_HOST"), config.MONGO_PORT);
this.db = m.getDB("cloud_datasource");
             db.authenticate(config.MONGO_USER, config.MONGO_PASS.toCharArray());
    } catch (Exception e) {
System.out.println("Can't connect to MongoDB");
             e.printStackTrace();

    }

In my config.properties: MONGO_HOST="192.168.10.84"

Problem: with this code, I have an error java.net.UnknownHostException: "192.168.10.84" but if I am using the code:

m = new Mongo("192.168.10.84", config.MONGO_PORT);

it works.


Solution

  • Try this (without quotes):

    MONGO_HOST=192.168.10.84