spring配置Mongodb
项目中需要配置mongodb,在网上找了很多资料,根据他们配置的一步一步往下走,总是会报错,Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Constructor threw exception; nested exception is java.lang.NoSuchFieldError: INSTANCE
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
… 30 more
类似这种问题,后来才发现是Spirng框架版和spring-data-mongodb的版本问题。
以下是我使用的版本配置成功的案例
1、先在pom.xml中注入以下两个版本的jar包。spring框架在4.3.4版本左右。
<!--MongoDB 开始-->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.14.3</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.7.RELEASE</version>
</dependency>
<!--MongoDB 结束-->
2、先看看项目原先的web.xml配置文件。
3、因为web.xml中已经配置好了扫描路径,会扫描spring文件下的以spring开始的xml文件 。所以我只要命名spring-mongodb.xml,就可以了,不用再向别人配置的那样在springmvc.xml中添加import导入资源文件了。
4、spring-monggodb.xml文件的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
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-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.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/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<mongo:mongo replica-set="服务器IP: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="true"
socket-keep-alive="true"
socket-timeout="${mongo.socketTimeout}"
slave-ok="true"
write-number="1"
write-timeout="0"
write-fsync="true"
/>
</mongo:mongo>
<mongo:db-factory dbname="test" mongo-ref="mongo"/>
<bean id="MongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
5、由于在spring.xml文件,所有config文件下的properties文件都会扫描到,所以在spring-mongodb.xml不需要再加载配置文件
6、启动没问题后,可以写代码了。