?
引入spring-data 依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
?
數(shù)據(jù)源配置,多個數(shù)據(jù)源
spring:
mongodb:
primary:
uri: mongodb://username1:password1@localost:27018/db1
secondary:
uri: mongodb://username2:password2@localost:27018/db2
thirdly:
uri: mongodb://username3:password3@localost:27018/db3
?
配置類
@Data public abstract class AbstractMongoConfig { private String uri; public abstract MongoTemplate mongoTemplate(); public MongoDbFactory mongoDbFactory(){ MongoClientURI mongoclienturi = new MongoClientURI(uri); return new SimpleMongoDbFactory(mongoclienturi); } }
?
@Configuration @ConfigurationProperties(prefix = "spring.data.mongodb.primary") public class PrimaryMongoConfig extends AbstractMongoConfig { @Primary //默認(rèn)會注入此數(shù)據(jù)源的Template @Override @Bean(name = "primaryMongoTemplate") public MongoTemplate mongoTemplate(){ return new MongoTemplate(mongoDbFactory()); } }
?
@Configuration @ConfigurationProperties(prefix = "spring.data.mongodb.secondary") public class SecondaryMongoConfig extends AbstractMongoConfig{ @Override @Bean(name = "secondaryMongoTemplate") public MongoTemplate mongoTemplate(){ return new MongoTemplate(mongoDbFactory()); } }
?
@Configuration @ConfigurationProperties(prefix = "spring.data.mongodb.thirdly") public class ThirdlyMongoConfig extends AbstractMongoConfig{ @Override @Bean(name = "thirdlyMongoTemplate") public MongoTemplate mongoTemplate(){ return new MongoTemplate(mongoDbFactory()); } }
?
注入MongoTemplate 進(jìn)行增刪改查
@Autowired private MongoTemplate mongoTemplate; @Autowired @Qualifier("secondaryMongoTemplate") private MongoTemplate template2; @Autowired @Qualifier("thirdlyMongoTemplate") private MongoTemplate template3;
?
本文摘自 :https://www.cnblogs.com/