Board logo

标题: Spring Boot配置MongoDB多数据源(1) [打印本页]

作者: look_w    时间: 2019-5-16 19:53     标题: Spring Boot配置MongoDB多数据源(1)

新建一个基础的抽象类

AbstractMongoConfigure.java
内容如下:

package com.biologic.util;

import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.MongoClient;

public abstract class AbstractMongoConfig {

    // 变量名跟配置的参数对应
    private String host, database, username, password;
    private int port;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    public MongoDbFactory mongoDbFactory() throws Exception {
        // 无认证的初始化方法
        return new SimpleMongoDbFactory(new MongoClient(host, port), database);

        // 有认证的初始化方法
        // ServerAddress serverAddress = new ServerAddress(host, port);
        // List<MongoCredential> mongoCredentialList = new ArrayList<>();
        // mongoCredentialList.add(MongoCredential.createCredential(username, database,
        // password.toCharArray()));
        // return new SimpleMongoDbFactory(new MongoClient(serverAddress,
        // mongoCredentialList), database);
    }


    /*
     * Factory method to create the MongoTemplate
     */
    abstract public MongoTemplate getMongoTemplate() throws Exception;

}
或者


public abstract class AbstractMongoConfig {

private String uri;
/*
     * Method that creates MongoDbFactory Common to both of the MongoDb
     * connections
     */
    public MongoDbFactory mongoDbFactory() throws Exception {

        return new SimpleMongoDbFactory(new MongoClientURI(uri);
    }

    /*
     * Factory method to create the MongoTemplate
     */
    abstract public MongoTemplate getMongoTemplate() throws Exception;




欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0