如何在" .propreties"中声明MongoDB配置文件?

时间:2016-03-01 16:32:57

标签: java mongodb java-ee spring-data

我是MongoDB和Spring Data的新手,通常普通关系数据库配置之间的连接是在.proprietes文件中完成的,例如:

# EMBEDDED SERVER CONFIGURATION
server.contextPath=/api

    # JPA
    spring.datasource.platform=org.hibernate.dialect.PostgreSQLDialect
    spring.jpa.show-sql=true
    spring.jpa.hibernate.ddl-auto=update
    spring.database.driverClassName=org.postgresql.Driver
    spring.datasource.url=jdbc:postgresql://localhost:5432/test
    spring.datasource.username=postgres
    spring.datasource.password=root

但是现在我已经迁移到MongoDB并且我已经成功地在其中插入了一个对象,但它是经典配置的(在main.java中),它就是这样的:

public class Application {
    public static final String DB_NAME = "TestDB";
    public static final String COMPTE_COLLECTION = "Compte";
    public static final String MONGO_HOST = "localhost";
    public static final int MONGO_PORT = 27017;

    public static void main(String[] args) throws UnknownHostException {

        try {
            MongoClient mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
            MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
            Compte p = new Compte("jon", "jon");
            mongoOps.insert(p, COMPTE_COLLECTION);

            System.out.println(p1);

            mongo.close();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

}

我想知道如何将上述MongoDB配置移到.proprieties文件中?我试图按原样放置它们并且它不起作用。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

正如您所见,文档:

# MONGODB (MongoProperties)
spring.data.mongodb.authentication-database= # Authentication database name.
spring.data.mongodb.database=test # Database name.
spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
spring.data.mongodb.grid-fs-database= # GridFS database name.
spring.data.mongodb.host=localhost # Mongo server host.
spring.data.mongodb.password= # Login password of the mongo server.
spring.data.mongodb.port=27017 # Mongo server port.
spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories.
spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. When set, host and port are ignored.
spring.data.mongodb.username= # Login user of the mongo server.

同样来自此链接connecting to mongo请注意:

  

如果您使用的是Mongo 3.0 Java驱动程序。在这种情况下,   应该使用spring.data.mongodb.uri来提供所有的   配置。