|
@@ -1,12 +1,15 @@
|
|
|
package com.mooctest.config;
|
|
|
|
|
|
+import com.mongodb.MongoClient;
|
|
|
import com.mongodb.MongoClientOptions;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.beans.factory.annotation.Qualifier;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
|
|
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
|
|
import org.springframework.context.annotation.Bean;
|
|
|
import org.springframework.context.annotation.Configuration;
|
|
|
+import org.springframework.context.annotation.Primary;
|
|
|
import org.springframework.core.env.Environment;
|
|
|
import org.springframework.data.mongodb.MongoDbFactory;
|
|
|
import org.springframework.data.mongodb.core.MongoTemplate;
|
|
@@ -18,30 +21,29 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie
|
|
|
@EnableMongoRepositories(
|
|
|
basePackages = "com.mooctest.dao2",
|
|
|
mongoTemplateRef = "mongoTemplate2")
|
|
|
-public class MongoTwoConfig {
|
|
|
-
|
|
|
- @Autowired
|
|
|
- private Environment environment;
|
|
|
+public class MongoTwoConfig{
|
|
|
+
|
|
|
+ @Value("${mongodb2.host}")
|
|
|
+ private String host;
|
|
|
+ @Value("${mongodb2.database}")
|
|
|
+ private String database;
|
|
|
+ @Value("${mongodb2.port}")
|
|
|
+ private int port;
|
|
|
+ //Setter methods go here..
|
|
|
+ /*
|
|
|
+ * 创建MongoDBFactory的方法
|
|
|
+ * 两个MongoDB连接共用
|
|
|
+ */
|
|
|
+ public MongoDbFactory mongoDbFactory2() throws Exception {
|
|
|
+ return new SimpleMongoDbFactory(new MongoClient(host, port), database);
|
|
|
+ }
|
|
|
|
|
|
|
|
|
- @Bean(name = "mongoTemplate2")
|
|
|
- public MongoTemplate mongoTemplate(@Qualifier("mongoFactory2") MongoDbFactory mongoFactory) throws Exception {
|
|
|
- return new MongoTemplate(mongoFactory);
|
|
|
- }
|
|
|
|
|
|
- @Bean("mongoFactory2")
|
|
|
- public MongoDbFactory mongoFactory(
|
|
|
- @Qualifier("mongoProperties2") MongoProperties mongoProperties) throws Exception {
|
|
|
- return new SimpleMongoDbFactory(
|
|
|
- mongoProperties.createMongoClient(MongoClientOptions.builder().build(), environment),
|
|
|
- mongoProperties.getDatabase());
|
|
|
+ public @Bean(name = "mongoTemplate2") MongoTemplate getMongoTemplate() throws Exception {
|
|
|
+ return new MongoTemplate(mongoDbFactory2());
|
|
|
}
|
|
|
|
|
|
- @Bean(name = "mongoProperties2")
|
|
|
- @ConfigurationProperties(prefix = "mongodb2")
|
|
|
- public MongoProperties properties() {
|
|
|
- return new MongoProperties();
|
|
|
- }
|
|
|
|
|
|
}
|
|
|
|