Commit 70eb2a20 by jwrwst

优化

parent 46963fe2
package com.cemarose.mongodb.config;
import com.mongodb.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.parsing.Location;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "spring.data.mongodb")
public class MongoConfig {
private String host;
private Integer port;
private String uri;
/**
* 初始化mongodb客户端
......@@ -17,7 +23,7 @@ public class MongoConfig {
*/
@Bean
public MongoClient client() {
return new MongoClient(new ServerAddress("127.0.0.1", 27017));
return new MongoClient(new ServerAddress(host, port));
}
/**
......@@ -27,7 +33,7 @@ public class MongoConfig {
*/
@Bean
public MongoDbFactory mongoDbFactory() throws Exception{
String database = new MongoClientURI("mongodb://localhost/dbtest").getDatabase();
String database = new MongoClientURI(uri).getDatabase();
return new SimpleMongoDbFactory(client(), database);
}
......@@ -41,13 +47,25 @@ public class MongoConfig {
return new MongoTemplate(mongoDbFactory);
}
/**
* test
*/
public void example(MongoDbFactory mongoDbFactory) {
DB db = mongoDbFactory.getDb();
DBCollection collection = db.getCollection("users");
//getter and setter
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment