hrishikeshp19
hrishikeshp19

Reputation: 9026

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?

Upvotes: 0

Views: 72

Answers (2)

Fritz Duchardt
Fritz Duchardt

Reputation: 11920

Treat it the same as a util class that you don't want to duplicate: move you config file to a separate project and make both your applications include that projects.

If you need to add additional project-specific configuration, Spring provides the @Import annotation that allows you to import configuration from separate classes, so you can create two project specific configuration classes that both import the generic configuration from the shared lib and supply their own individual beans and property sources, e.g.:

@Configuration
@PropertySource("classpath:/com/appspecific/app.properties")
@Import(com.genericlib.BaseConfig.class)
public class AppConfig {
 @Inject BaseConfig baseConfig;

 @Bean
 public MyBean myBean() {
     // reference the base config context
     return new MyBean(baseConfig.getSomething());
 }
}

Upvotes: 1

Use Spring Boot, and optionally include the @PropertySource to add to the environment. It will collect all the MongoDB information and configure a client and template for you.

Upvotes: 0

Related Questions