1、環境配置: Mongodb安裝: 1)、下載 地址:http://www.mongodb.org/downloads 2)、安裝 安裝指南:http://docs.mongodb.org/manual/installation/ 步驟: 在/data目錄下建立/data/mongodb/data、以及/data/mongodb/log目錄 解壓:tar -zxvf mongodb-linux-x86_64-2.2.2.tar 進入mongodb的bin的目錄下執行以下命令: ./mongod --dbpath /data/mongodb/data --logpath /data/mongodb/log/mongo.log --logappend2、Spring data mongodb包下載 地址:http://s3.amazonaws.com/dist.springframework.org/release/SDMONGO/spring-data-mongo-1.1.0.RELEASE.zip Spring data common jar包下載: 地址:http://s3.amazonaws.com/dist.springframework.org/milestone/DATACMNS/spring-data-commons-1.4.0.RC1.zip3、Mongodb的java驅動包下載: 地址:https://github.com/mongodb/mongo-java-driver/downloads4、所需jar包: aopalliance-1.0.jar、asm-all-3.3.1.jar、cglib-2.2.2.jar、slf4j-api-1.7.1.jar、slf4j-log4j12-1.6.1.jar、slf4j-nop-1.5.8.jar、 commons-logging.jar、log4j-1.2.9.jar、Spring Framework jar包、mongo-2.10.1.jar、Spring data mongodb的相關jar包、Spring data common的jar包5、建立Spring_mongodb java項目,將以上jar包匯入其中。 配置mongodb由Spring管理有兩種方法: 1)、使用@Configuration註解來進行配置: 這裡需要建立一個配置類,返回一個MongodbFactory對象、如:
@Configurationpublic class AppConfig {public @Bean MongoOperations mongoTemplate(Mongo mongo) { MongoTemplate mongoTemplate = new MongoTemplate(mongo, "test"); return mongoTemplate; }/* * Factory bean that creates the Mongo instance */ public @Bean MongoFactoryBean mongo() { MongoFactoryBean mongo = new MongoFactoryBean(); mongo.setHost("localhost"); return mongo; }/* * Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes */ public @Bean PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() { return new PersistenceExceptionTranslationPostProcessor(); }}
2)、使用XML形式配置:
<?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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><context:annotation-config/><context:component-scan base-package="com.springdb.mongodb"><context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/></context:component-scan><bean id="mongoTemplate"><constructor-arg name="mongo" ref="mongo"/><constructor-arg name="databaseName" value="test"/></bean><!-- Factory bean that creates the Mongo instance --><bean id="mongo"><property name="host" value="192.168.130.170"/><property name="port" value="27017"/></bean><!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes --><bean/></beans>
執行個體地址下載:http://download.csdn.net/detail/weijonathan/5045391