Wednesday, March 5, 2014

Spring Annotation based configuration - reading from property file

Spring can be configured using context xml files or using java annotations.

@Configuration can be used if you want to configure using java.

Full configuration code:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.cv")
@EnableMongoRepositories(basePackages = { "com.cv.framework.mongorepositories",
              "com.cv.app.repository" })
@PropertySource(value = "classpath:app.properties")
public class AppConfig extends WebMvcConfigurerAdapter
       @Inject
       Environment environment;
       @Bean
       public InternalResourceViewResolver configureInternalResourceViewResolver() {
              InternalResourceViewResolver resolver = new InternalResourceViewResolver();
              resolver.setPrefix("/WEB-INF/views/");
              resolver.setSuffix(".jsp");
              return resolver;
       }
       @SuppressWarnings("deprecation")
       @Bean
       public Mongo mongo() throws Exception {
              return new Mongo(environment.getProperty("ip"));
       }

       @Bean
       public MongoTemplate mongoTemplate() throws Exception {
              return new MongoTemplate(mongo(),
                           environment.getProperty("mdbname"));
       }

}

@Configuration tells that the current java file is a spring configuration file. 
@ComponentScan tells the container to scan all the java files that starts with the package com.cv

@EnableMongoRepository informs the container where to search for mongo Repositories. 

@PropertySource annotation defines the property file this annotation java file uses to pull configurable values for the application. 

Environment is a spring api class which is used to read from the properties file. 
environment.getProperty("mdbname") tries to read the property mdbname from the app.properties file. 

Java based spring configuration is easier than the xml configuration since it throws all the errors at compile time and the context sensitive help comes very handy. 

Some developers prefer to keep some configuration in the xml to locate easily. 



No comments:

Post a Comment