您好,我正在尝试MongoClient
在 Spring Boot 中成功连接后导出它,并且我正在尝试在其他文件中使用它,这样我就不必每次需要在我的 MongoDB 数据库中进行更改时都调用该连接。
连接非常简单,但目标是将应用程序连接到我的数据库一次,然后通过在任何 Java 文件中导入它来在任何我想要的地方使用它。
谢谢
您好,我正在尝试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 API 处理 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
代表test3
集合文档的POJO 类:
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);
}
**Pom Changes :**
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- jpa, crud repository -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
**Main Application :**
@SpringBootApplication(exclude = {
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class
})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
**MongoConfig Class :**
@Configuration
@EnableMongoRepositories({"com.repository.mongo"})
public class MongoConfig {
private final MongoProperties properties;
public MongoConfig(MongoProperties properties) {
this.properties = properties;
}
@Bean
public MongoClient mongo() throws IOException {
log.info("Creating mongo client. Socket timeout: {}, request timeout: {}",
properties.getSocketTimeout(), properties.getConnectTimeout()
);
MongoCredential credential = MongoCredential.createCredential(properties.getUsername(), properties.getDatabase(), readPassword(properties.getPasswordFilePath()).toCharArray());
MongoClientSettings settings = MongoClientSettings.builder()
.credential(credential)
.applyToSocketSettings(builder -> builder.readTimeout(properties.getSocketTimeout().intValue(), TimeUnit.MILLISECONDS).connectTimeout(properties.getConnectTimeout().intValue(), TimeUnit.MILLISECONDS))
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(new ServerAddress(properties.getHost(), properties.getPort()))).requiredReplicaSetName(properties.getReplicaSet()))
.build();
return MongoClients.create(settings);
}
@Bean
public MongoDatabase database() throws IOException {
// Allow POJOs to be (de)serialized
CodecRegistry extendedRegistry = fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build())
);
return mongo().getDatabase(properties.getDatabase()).withCodecRegistry(extendedRegistry);
}
@Bean
public MongoTemplate mongoTemplate() throws IOException {
return new MongoTemplate(mongo(), properties.getDatabase());
}
@PreDestroy
public void destroy() throws IOException {
mongo().close();
}
private String readPassword(String path) throws IOException {
// return Files.readString(Paths.get(path));
return "****";
}
}