I am using the below Spring configuration in order to connect to mongoDB
To update @Lealem Admassu's answer for java config, in Mongo 3 they changed the API, and now it is recommended to use mongo's MongoCredentials instead of UserCredentials.
Here there is a simple example of how to get a MongoClient: http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.mongo-3.authentication
The next code can be done modular, but more or less this works for me (I needed a MongoTemplate):
public MongoTemplate getMongoTemplate(String host, int port,
String authenticationDB,
String database,
String user, char[] password)
throws UnknownHostException {
return new MongoTemplate(
new SimpleMongoDbFactory(
new MongoClient(
new ServerAddress(host, port),
Collections.singletonList(
MongoCredential.createCredential(
user,
authenticationDB,
password
)
)
),
database
)
);
}