1、在pom中加入spring-data的依赖
<dependencies>
<!-- other dependency elements omitted -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.1.0.RELEASE</version>
</dependency>
</dependencies>
并在通dependencies同层次加入spring的repository来下载相关的依赖包
<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>http://repo.springsource.org/libs-milestone</url>
</repository>
</repositories>
2、在spring配置文件中定义mongoDB的相关信息,并注册MongoTemplate
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<!-- mongo configure start -->
<mongo:mongo host="localhost" port="30000">
</mongo:mongo>
<mongo:db-factory dbname="weather" mongo-ref="mongo" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
</beans>
MongoTemplate的重载的构造方法.如下所示:
MongoTemplate (Mongo mongo, String databaseName) - takes the com.mongodb.Mongo object and the default database name to operate against.
MongoTemplate (Mongo mongo, String databaseName, UserCredentials userCredentials) - adds the username and password for authenticating with the database.
MongoTemplate (MongoDbFactory mongoDbFactory) - takes a MongoDbFactory object that encapsulated the com.mongodb.Mongo object, database name, and username and password.
MongoTemplate (MongoDbFactory mongoDbFactory, MongoConverter mongoConverter) - adds a MongoConverter to use for mapping.
也可以通过如下的方式定义MongoTemplate
<mongo:mongo host="localhost" port="27017"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo"/>
<constructor-arg name="databaseName" value="geospatial"/>
</bean>