jeudi 28 mai 2015

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:

@Configuration
@PropertySource("file:/etc/x/y/mongodb.properties")
public class MongoConfiguration {

    @Autowired
    private Environment env;

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

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

    @Bean(name="mongoTemplate")
    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?

Aucun commentaire:

Enregistrer un commentaire