Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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;
        }
    }

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());
    }
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top