工程的核心配置还是使用xml,跟mongoDB相关的部分如下:
[color=red][size=medium]当看到这样的异常时,说明需要配置Converter了:
org.springframework.data.mapping.model.MappingException[/size][/color]
<?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"
xmlns:context="http://www.springframework.org/schema/context"
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"
default-lazy-init="true">
<!-- 这个bean默认的名称是mongo -->
<mongo:mongo host="11.11.11.13" port="27017" replica-set="11.11.11.13:27018,11.11.11.11:27019">
<mongo:options connections-per-host="8"
threads-allowed-to-block-for-connection-multiplier="4"
connect-timeout="3000"
max-wait-time="3000"
auto-connect-retry="true"
socket-keep-alive="true"
socket-timeout="3000"
slave-ok="true"
write-number="1"
write-timeout="0"
write-fsync="true"></mongo:options>
</mongo:mongo>
<!-- 配置一个MongoDbFactory,u数据库名叫mydb,mongo-ref指向mongo -->
<!-- 这个东西就是上面那个mongo:mongo配置的bean -->
<mongo:db-factory dbname="mydb" mongo-ref="mongo"/>
<!-- 这里配置了一个货币的转换器,主要是将bson转换成Currency类型 -->
<!-- 主要用于Currency这个类型属性的序列化和反序列化 -->
<bean id="currencyMappingMongoReadConverter"
class="test.converter.CurrencyReadConverter"/>
<!-- 这个bean的默认名称是mappingConverter,是mongo converter的集合 -->
<!-- 一般只需要指定自定义的converter,converter一般分两种read和write,看spring的文档。-->
<mongo:mapping-converter>
<mongo:custom-converters>
<mongo:converter ref="currencyMappingMongoReadConverter"/>
</mongo:custom-converters>
</mongo:mapping-converter>
<!-- 这个bean的默认名称是mongoTemplate -->
<!-- 类似于spring里的jdbcTemplate,需要注入MongoDbFactory -->
<!-- mongoConverter不是必须的 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg index="0" name="mongoDbFactory"
type="org.springframework.data.mongodb.MongoDbFactory" ref="mongoDbFactory"/>
<constructor-arg index="1" name="mongoConverter"
type="org.springframework.data.mongodb.core.convert.MongoConverter"
ref="mappingConverter"/>
</bean>
<beans>
[color=red][size=medium]当看到这样的异常时,说明需要配置Converter了:
org.springframework.data.mapping.model.MappingException[/size][/color]