springboot2.5.0集成spring-data-mongodb 4.3.2
集成mongodb
网上都是比较老版本的spring-data-mongodb, 其中mongodb客户端的生成MongoDbFactory接口已经是过时的接口, 新的接口没有在网上找到相关匹配内容。
pom.xml文件引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>2.5.0</version>
</dependency>
其中配置的mongodb驱动为4.3.2版本
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.2.3</version>
<scope>compile</scope>
</dependency>
application.properties配置文件
test.mongodb.uri=mongodb://username:password@ip:port/dbName
test1.mongodb.uri=mongodb://username:password@ip:port/dbName
mongo配置类生产MongoTemplate
@Configuration
public class MongoConfig {
@Value("${test.mongodb.uri}")
private String mongoUri;
@Value("${test1.mongodb.uri}")
private String mongoUri1;
@Bean(name="mongoDatabaseFactory")
@Primary
MongoDatabaseFactory mongoDatabaseFactory(){
return new SimpleMongoClientDatabaseFactory(mongoUri);
}
@Bean(name="mongoDatabaseFactory1")
MongoDatabaseFactory mongoDatabaseFactory1(){
return new SimpleMongoClientDatabaseFactory(mongoUri1);
}
@Bean(name = "mongoTemplate")
@Primary
MongoTemplate mongoTemplate(){
return new MongoTemplate(mongoDatabaseFactory());
}
@Bean(name = "mongoTemplate1")
MongoTemplate mongoTemplate1(){
return new MongoTemplate(mongoDatabaseFactory1());
}
}
服务调用
@Service
public class MongoService {
@Autowired
@Qualifier("mongoTemplate")
private MongoTemplate mongoTemplate;
@Autowired
@Qualifier("mongoTemplate1")
private MongoTemplate mongoTemplate1;
public List<Test> findAll(){
return mongoTemplate.findAll(Test.class);
}
public List<Test> findAll1(){
return mongoTemplate1.findAll(Test.class);
}
}
上述只是测试, 工作中还是将MongoTemplate分成两个类的好.
|