日期:2014-05-16 浏览次数:20702 次
package com.mkyong.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.document.mongodb.MongoTemplate; import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration; import com.mongodb.Mongo; /** * Spring MongoDB configuration file * */ @Configuration public class SpringMongoConfig extends AbstractMongoConfiguration { @Override public @Bean Mongo mongo() throws Exception { return new Mongo("localhost"); } @Override public @Bean MongoTemplate mongoTemplate() throws Exception { return new MongoTemplate(mongo(),"yourdb","yourCollection"); } }
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class); MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
<?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"> <!-- Default bean name is 'mongo' --> <mongo:mongo host="localhost" port="27017" /> <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> <constructor-arg ref="mongo" /> <constructor-arg name="databaseName" value="yourdb" /> <constructor-arg name="defaultCollectionName" value="yourCollection" /> </bean> <!-- To translate any MongoExceptions thrown in @Repository annotated classes --> <context:annotation-config /> </beans>
package com.mkyong.user; public class User { private String id; private String firstname; private String lastname; private int age; //getter and setter methods }
package com.mkyong.core; import java.util.List; import org.springframework.context.Applicati