引入spring-data 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
数据源配置,多个数据源
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 //默认会注入此数据源的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 进行增删改查
@Autowired private MongoTemplate mongoTemplate; @Autowired @Qualifier("secondaryMongoTemplate") private MongoTemplate template2; @Autowired @Qualifier("thirdlyMongoTemplate") private MongoTemplate template3;