mongodb与spring集成

1、pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.datagroupId>
        <artifactId>spring-data-mongodbartifactId>
        <version>2.0.8.RELEASEversion>
    dependency>
dependencies>

2、spring.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:mongo="http://www.springframework.org/schema/data/mongo"
      xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   <mongo:mongo-client id="mongoClient"  host="172.25.16.117" port="27017"
                  credentials="member:password@member"/>
   <mongo:db-factory id="mongoDbFactory" dbname="member" mongo-ref="mongoClient"/>
   <mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory" write-concern="NORMAL"/>
beans>

3、测试类:

package com.zehao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
 * Created by 11072706 on 2018/7/12.
 * @version: branch_member_20180613_v3_2_0
 */
public class Test {

    public static void main(String[] args) {
        ApplicationContext ap = new ClassPathXmlApplicationContext("spring.xml");
        MongoTemplate mongoTemplate  = ap.getBean("mongoTemplate", MongoTemplate.class);
        System.out.println(mongoTemplate.getDb().getName());
    }
}

4、控制台输出:

member

你可能感兴趣的:(mongodb)