Apparently, most of the visitors to my “Integrating MongoDB with Spring Batch” post can’t find what they look for, because they look for instructions how to integrate MongoDB with plain Spring Core.
Well, the source includes that integration, but it’s on github, and anyway that wasn’t the focus of that post.
So, here’s the integration – short, plain and simple:
- Properties file with server and database details (resides in classpath in this example):
1 db.host=localhost 2 db.port=27017 3 app.db.name=app
- If you don’t use Java-based container configuration (you should start using it!):
- application-config.xml (or whatever you call it):
1<beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 6 http://www.springframework.org/schema/context 7 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 8 <context:property-placeholder 9 location="classpath:db.properties"/> 10 <bean id="mongo" class="com.mongodb.Mongo"> 11 <constructor-arg value="${db.host}"/> 12 <constructor-arg value="${db.port}"/> 13 </bean> 14 <bean id="db" 15 class="com.mongodb.spring.config.DbFactoryBean"> 16 <property name="mongo" ref="mongo"/> 17 <property name="name" value="${app.db.name}"/> 18 </bean> 19</beans>
- The com.mongodb.spring.config.DbFactoryBean class:
1 public class DbFactoryBean implements FactoryBean<DB> { 2 3 private Mongo mongo; 4 private String name; 5 6 @Override 7 public DB getObject() throws Exception { 8 return mongo.getDB(name); 9 } 10 11 @Override 12 public Class<?> getObjectType() { 13 return DB.class; 14 } 15 16 @Override 17 public boolean isSingleton() { 18 return true; 19 } 20 21 public void setMongo(Mongo mongo) { 22 this.mongo = mongo; 23 } 24 25 public void setName(String name) { 26 this.name = name; 27 } 28 }
- If you do use Java-based container configuration – here’s your @Configuration class:
1 @Configuration 2 public class ApplicationConfiguration { 3 4 @Value("${app.db.name}") 5 private String appDbName; 6 7 @Value("${db.host}") 8 private String dbHost; 9 10 @Value("${db.port}") 11 private int dbPort; 12 13 14 @Bean 15 public DB db() throws UnknownHostException { 16 return mongo().getDB(appDbName); 17 } 18 19 @Bean 20 public Mongo mongo() throws UnknownHostException { 21 return new Mongo(dbHost, dbPort); 22 } 23 }
That’s, actually, it – enjoy. If you feel some part of the puzzle is missing, please leave a comment.
Filed under: Frameworks, Friendly Java Blogs Tagged: java, mongodb, spring
