<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.0.4.RELEASE</version> </dependency>
Application設定
@SpringBootApplication( exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class} ) public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }最重要的就是要設定 exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class}
application.properties設定
mongodb.connect1.uri=mongodb://自己的連線設定1 mongodb.connect1.database=自己的database1 mongodb.connect2.uri=mongodb://自己的連線設定2 mongodb.connect2.database=自己的database2
Configurer設定
@Configuration public class TestConfigurer{ @Bean @ConfigurationProperties(prefix = "mongodb.connect1") public MongoProperties getConnectionSetting1() { return new MongoProperties(); } @Bean @ConfigurationProperties(prefix = "mongodb.connect2") public MongoProperties getConnectionSetting2() { return new MongoProperties(); } @Bean(name="Template1") public MongoTemplate mongoTemplate1(){ MongoProperties p = getConnectionSetting1(); return genMongoTemplateWithMongoProperties(p); } @Bean(name="Template2") public MongoTemplate mongoTemplate2(){ MongoProperties p = getConnectionSetting2(); return genMongoTemplateWithMongoProperties(p); } private MongoTemplate genMongoTemplateWithMongoProperties(MongoProperties p){ MongoClientURI uri = new MongoClientURI(p.getUri()); MongoClient client = new MongoClient(uri); SimpleMongoDbFactory f = new SimpleMongoDbFactory(client, p.getDatabase()); return new MongoTemplate(f); } }
Dao使用Template
@Repository public class TestDao { @Autowired @Qualifier("Template1") private MongoTemplate mongoTemplate1; @Autowired @Qualifier("Template2") private MongoTemplate mongoTemplate2; }
沒有留言:
張貼留言