Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

java - How to initialize MongoClient once in Spring Boot and use its methods?

Hello I am trying to export the MongoClient after a successful connection in Spring Boot and I am trying to use it in other files so that I do not have to call the connection every single time that I need to make changes in my MongoDB database.

The connection is pretty simple but the goal would be to connect the application to my database once and then use it wherever I want by importing it in any Java file.

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here are couple of ways of creating an instance of MongoClient, configuring and using it within the Spring Boot application.

(1) Registering a Mongo Instance using Java-based Metadata:

@Configuration
public class AppConfig {
    public @Bean MongoClient mongoClient() {
        return MongoClients.create();
    }
}

Usage from CommandLineRunner's run method (all examples are run similarly):

@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) Configure using AbstractMongoClientConfiguration class and use with MongoOperations:

@Configuration
public class MongoClientConfiguration extends AbstractMongoClientConfiguration {

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create();
    }

    @Override
    protected String getDatabaseName() {
        return "newDB";
    }
}

Note you can set the database name (newDB) you can connect to. This configuration is used to work with MongoDB database using Spring Data MongoDB APIs: MongoOperations (and its implementation MongoTemplate) and the 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) Configure using AbstractMongoClientConfiguration class and use with MongoRepository

Using the same configuration MongoClientConfiguration class (above in topic 2), but additionally annotate with @EnableMongoRepositories. In this case we will use MongoRepository interface methods to get collection data as Java objects.

The repository:

@Repository
public interface MyRepository extends MongoRepository<Test3, String> {

}

The Test3.java POJO class representing the test3 collection's document:

public class Test3 {

    private String id;
    private String fld;

    public Test3() {    
    }

    // Getter and setter methods for the two fields
    // Override 'toString' method
    ...
}

The following method to get documents and print as Java objects:

@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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...