MongoDB 和Spring的 结合第一步经常出现错误:jar包的版本问题。
下面贴出两者整合的一套参考Version。
使用的是【Spring 3.1.2.RELEASE 版本】 + 【spring-data-mongodb 1.3.0.RELEASE】 + 【mongo-java-driver 2.11.1】
- Maven的配置文件pom.xml
<!-- MongoDB --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.11.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.0</version> </dependency> <!--Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.1.2.RELEASE</version> </dependency>
Spring 的配置文件如下 (在配置文件中只需要涉及到库名的配置,相对应collection中在代码中可以指定)
<?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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <mongo:mongo host="localhost" port="27017"> <mongo:options connections-per-host="200" threads-allowed-to-block-for-connection-multiplier="100" connect-timeout="1000" max-wait-time="1500" auto-connect-retry="true" socket-keep-alive="true" socket-timeout="1500" slave-ok="true" write-number="1" write-timeout="0" write-fsync="true" /> </mongo:mongo> <mongo:db-factory dbname="***" username="***" password="****" mongo-ref="mongo" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> </bean> <bean id="abstractMongoDB" class="com.***.AbstractMongoDB" abstract="true"> <property name="mongoTemplate"> <ref bean="mongoTemplate" /> </property> </bean> </beans>
本篇最后的话:
该文章只贴出 spring 和 mongodb 整合匹配的版本VERSION (提供一个参考项目)。