@Configuration public 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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://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