Mongodb java利用spring访问mongodb

1. 需要先外mongodb的配置文件修改下:

vi /etc/mongod.conf将bind_ip这一行去掉或改成客户端的ip,允许其他ip可以访问mongo

 

2.maven引入spring-data-mongodb包

 

3. 在spring的配置文件中增加以下内容:

 <mongo:mongo host="10.1.5.105" port="27017">
 </mongo:mongo>

 <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  <constructor-arg ref="mongo" />
  <constructor-arg name="databaseName" value="mydb" />
 </bean>

 

4.这样便可以在application上下文中使用了:

@Controller
@RequestMapping("/MongoController")
public class MongoController {
 @Resource
 private MongoService mongoService;
 @Resource
 private MongoTemplate mongoTemplate;

 @RequestMapping(value = "index", method = RequestMethod.GET)
 public String index(HttpSession session, ModelMap model) {

  mongoTemplate.insert(new Person("2","kevin", 34));
  
  return "index";
 }
}

 

备注:

spring头部:

<?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:mvc="http://www.springframework.org/schema/mvc"

xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"

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.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-4.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

http://www.springframework.org/schema/data/mongo 

http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">

猜你喜欢

转载自qingwei201314.iteye.com/blog/2184928