zno2

mongodb spring 集成

参考文档

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

依赖

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.0.2</version>
        </dependency>

 

beans-mongodb.xml

    <beans>
        <bean class="cn.zno.mongodb.CustomMongoClient" init-method="init" destroy-method="destroy" scope="singleton">
            <property name="uri">
               <value><![CDATA[mongodb://xiaoming:123456@localhost:27017/?authSource=logtest&authMechanism=MONGODB-CR]]></value>
            </property>
            <property name="dbName" value="logtest"></property>
            <property name="collectionName" value="news"></property>            
        </bean>
    </beans>

 

CustomMongoClient.java

package cn.zno.mongodb;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;

public class CustomMongoClient {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    
    private MongoClient mongoClient;
    private MongoCollection<Document> mongoCollection;

    private String uri;
    private String dbName;
    private String collectionName;

    public void init() {
        MongoClientURI mongoClientURI = new MongoClientURI(uri);
        mongoClient = new MongoClient(mongoClientURI);
        mongoCollection = mongoClient.getDatabase(dbName).getCollection(collectionName);
        logger.info("MongoClient init");
    }

    public void destroy() {
        mongoClient.close();
        logger.info("MongoClient closed");
    }

    public MongoCollection<Document> getCollection() {
        return this.mongoCollection;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getDbName() {
        return dbName;
    }

    public void setDbName(String dbName) {
        this.dbName = dbName;
    }

    public String getCollectionName() {
        return collectionName;
    }

    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }
}

 

如何使用:

    @Autowired
    private CustomMongoClient mongoClient;

    public void dd() {
        Document document = new Document();
        document.append("title", "天气日报");
        document.append("content", "晴");
        mongoClient.getCollection().insertOne(document);
    }

 

posted on 2016-08-05 17:57  zno2  阅读(215)  评论(0编辑  收藏  举报

导航