IOC containers: de-duplicating the configuration code

I am using spring framework for 2 different applications. Let’s say both of the applications talk to one single MongoDB database. Following is how I configure MongoDB in both the applications:

public class MongoConfiguration {

    private Environment env;

    public UserCredentials mongoCredentials() {
        String mongoUserName = env.getProperty("mongodb.username");
        String mongoPassword = env.getProperty("mongodb.password");
        UserCredentials credentials = new UserCredentials(mongoUserName, mongoPassword);
        return credentials;

    public MongoClient mongoClient() throws Exception {
        String mongoUrl = env.getProperty("mongodb.url");
        String mongoPort = env.getProperty("mongodb.port");
        MongoClient mongo = new MongoClient(mongoUrl, Integer.valueOf(mongoPort));
        return mongo;

    public MongoTemplate mongoTemplate() throws Exception {
        String mongoDatabaseName = env.getProperty("mongodb.databasename");
        MongoTemplate mongoTemplate = new MongoTemplate(mongoClient(), mongoDatabaseName, mongoCredentials());
        return mongoTemplate;

Now, this piece of code is duplicated in two different application configurations. How do I avoid doing this configuration at two different places?

Source: oop

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.