這裡我們用到的是spring-data中一個整合mongodb的項目,首先在maven中添加對它的依賴,這裡我用的是1.0.0.M5版本
<!-- mongodb spring --><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-mongodb</artifactId><version>1.0.0.M5</version></dependency>
然後是設定檔
<?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:context="http://www.springframework.org/schema/context"xmlns:mongo="http://www.springframework.org/schema/data/mongo"xsi:schemaLocation="http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/data/mongohttp://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><context:property-placeholder location="classpath*:META-INF/mongodb/mongodb.properties"/><!-- 定義mongo對象,對應的是mongodb官方jar包中的Mongo,replica-set設定叢集副本的ip地址和連接埠 --><mongo:mongo id="mongo" replica-set="localhost:27017"><!-- 一些串連屬性的設定 --><mongo:options connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}" socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}" write-number="1" write-timeout="0" write-fsync="true"/></mongo:mongo><!-- mongo的工廠,通過它來取得mongo執行個體,dbname為mongodb的資料庫名,沒有的話會自動建立 --><mongo:db-factory dbname="test" mongo-ref="mongo"/><!-- mongodb的主要操作對象,所有對mongodb的增刪改查的操作都是通過它完成 --><bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/></bean><!-- 映射轉換器,掃描back-package目錄下的檔案,根據注釋,把它們作為mongodb的一個collection的映射 --><mongo:mapping-converter base-package="com.xxx.xxx.domain" /><!-- mongodb bean的倉庫目錄,會自動掃描擴充了MongoRepository介面的介面進行注入 --><mongo:repositories base-package="com.xxx.xxx.persist.mongodb"/><!-- To translate any MongoExceptions thrown in @Repository annotated classes --><context:annotation-config /> </beans>
這樣基本配置就完成了,其它深入操作將在後續文章中說明。