你好,我正在尝试导出 MongoClient
在Spring Boot中连接成功后,我试图在其他文件中使用它,这样我就不必每次在MongoDB数据库中进行更改时都要调用该连接。
该连接非常简单,但目标是将应用程序连接到我的数据库一次,然后通过在任何Java文件中导入它来使用它。
谢谢你的帮助
这里有几种方法来创建一个实例 MongoClient
,配置并在Spring Boot应用程序中使用它。
(1) 使用基于Java的元数据注册Mongo实例。
@Configuration
public class AppConfig {
public @Bean MongoClient mongoClient() {
return MongoClients.create();
}
}
使用来自 CommandLineRunner
's run
方法 (诸如此类):
@Autowired
MongoClient mongoClient;
// Retrieves a document from the "test1" collection and "test" database.
// Note the MongoDB Java Driver API methods are used here.
private void getDocument() {
MongoDatabase database = client.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("test1");
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());
}
(2) 使用AbstractMongoClientConfiguration类进行配置,并与MongoOperations一起使用。
@Configuration
public class MongoClientConfiguration extends AbstractMongoClientConfiguration {
@Override
public MongoClient mongoClient() {
return MongoClients.create();
}
@Override
protected String getDatabaseName() {
return "newDB";
}
}
注意你可以设置数据库名称(newDB
)你可以连接到。此配置用于使用Spring Data MongoDB APIs与MongoDB数据库合作。MongoOperations
(以及它的实现 MongoTemplate
)和 MongoRepository
.
@Autowired
MongoOperations mongoOps;
// Connects to "newDB" database, and gets a count of all documents in the "test2" collection.
// Uses the MongoOperations interface methods.
private void getCollectionSize() {
Query query = new Query();
long n = mongoOps.count(query, "test2");
System.out.println("Collection size: " + n);
}
(3) 使用AbstractMongoClientConfiguration类进行配置,并与MongoRepository一起使用。
使用相同的配置 MongoClientConfiguration
类 (上文第2题),但另外用 @EnableMongoRepositories
. 在这种情况下,我们将使用 MongoRepository
接口方法,以Java对象的形式获取集合数据。
储存库。
@Repository
public interface MyRepository extends MongoRepository<Test3, String> {
}
储存库: Test3.java
代表POJO类的 test3
集合的文档。
public class Test3 {
private String id;
private String fld;
public Test3() {
}
// Getter and setter methods for the two fields
// Override 'toString' method
...
}
下面的方法可以得到文档并打印成Java对象。
@Autowired
MyRepository repository;
// Method to get all the `test3` collection documents as Java objects.
private void getCollectionObjects() {
List<Test3> list = repository.findAll();
list.forEach(System.out::println);
}