mbird mbird -4 years ago 163
Java Question

Spring Data : Java configuration for MongoDB without XML

I tried the Spring Guide Accessing Data with MongoDB. What I can't figure out is how do I configure my code to not use the default server address and not use the default database. I have seen many ways to do it with XML but I am trying to stay with fully XML-less configurations.

Does anyone have an example that sets the server and database without XML and can be easily integrated into the sample they show in the Spring Guide?

Note: I did find how to set the collection (search for the phrase "Which collection will my documents be saved into " on this page.

Thank you!

p.s. same story with the Spring Guide for JPA -- how do you configure the db properties -- but that is another post :)

Answer Source

It would be something like this for a basic configuration :

public class MongoConfiguration extends AbstractMongoConfiguration {

    protected String getDatabaseName() {
        return "dataBaseName";

    public Mongo mongo() throws Exception {
        return new MongoClient("", 27017);

    protected String getMappingBasePackage() {
        return "foo.bar.domain";

Example for a document :

public class Person {

    private String id;

    private String name;

    public Person(String name) {
        this.name = name;

    public String getId() {
        return id;

    public void setId(String id) {
        this.id = id;

    public String getName() {
        return name;

    public void setName(String name) {
        this.name = name;

Example for a repository :

public class PersonRepository {

    MongoTemplate mongoTemplate;

    public long countAllPersons() {
        return mongoTemplate.count(null, Person.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download