Setting up and using MongoDB in the Spring application is a simple two step process.Specify the Mongo template in the application configuration , then customize the ApplicationConfig .
Step 1
Include the Mongo configuration in the application context
<mongo:db-factory id="mongoDbFactory" dbname="my-store" /> <mongo:mapping-converter id="mongoConverter" base-package="springdata.mongodb"> <mongo:custom-converters base-package="springdata.mongodb" /> </mongo:mapping-converter> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> <constructor-arg ref="mongoConverter" /> <property name="writeConcern" value="SAFE" /> </bean> <mongo:repositories base-package="springdata.mongodb" />Step2 Setup the ApplicationConfig in the base-package
@ComponentScan
@EnableMongoRepositories
class ApplicationConfig extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "my-store";
}
@Override
public Mongo mongo() throws Exception {
Mongo mongo = new Mongo();
mongo.setWriteConcern(WriteConcern.SAFE);
return mongo;
}
}
After the two steps the Mongo can be included in the application by simply autowiring
@Autowired Mongo mongo;
No comments:
Post a Comment