1

i try to connect to mongohq using spring. i got some information from heroku but while connecting with that code MongoURI class are deprecated . I used spring-data-mongodb version 1.2.0.RELEASE. and mongo-java-driver - 2.11.0

can any one tell how to connect to mongohq or mongolab using spring

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
bhv
  • 5,188
  • 3
  • 35
  • 44

4 Answers4

3

Hear is the code..

@Configuration
    public class SpringConfig {
        @Bean
        public DB getDb() throws UnknownHostException, MongoException {
            String uri="mongodb://user:password@id.mongolab.com:53178/db";
            MongoClientURI mongoClientURI=new MongoClientURI(uri);
            MongoClient mongoClient=new MongoClient(mongoClientURI);
            DB db=mongoClient.getDB(mongoClientURI.getDatabase());
            db.authenticate(mongoClientURI.getUsername(),mongoClientURI.getPassword());
            return db;
        }
    }
bhv
  • 5,188
  • 3
  • 35
  • 44
0

As you can read in the MongoURI documentation

public class MongoURI extends Object

Represents a URI which can be used to create a Mongo instance. The URI describes the hosts to be used and options.

This class has been superseded by MongoClientURI, and may be deprecated in a future release.

So MongoClientURI is your answer

zero323
  • 322,348
  • 103
  • 959
  • 935
0

If you use mongodb with Spring Data Mongodb you can use a configuration as described in http://docs.spring.io/spring-data/data-mongo/docs/1.4.1.RELEASE/reference/html/mongo.core.html#mongo.mongo-db-factory-java

It will finally look like :

@Configuration
public class MongoHQConfiguration {

    public @Bean MongoDbFactory mongoDbFactory() throws MongoException, UnknownHostException {
        return new SimpleMongoDbFactory(new MongoURI(System.getenv("MONGOHQ_URL")));
    }

    public @Bean MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}
lforet
  • 16
  • 2
0

If you are using Spring Boot, the class "MongoProperties" is just waiting for an external configuration:

With "heroku config" you can see properties already defined - there will be a "MONGOLAB_URI" if MongoLab was added to your application.

Just define: heroku config:set spring.data.mongodb.uri=< MONGOLAB_URI >. Done.

Romain F.
  • 766
  • 10
  • 15