How to initialize MongoClient once in spring boot and export it to use its methods?

点点圈 提交于 2021-02-12 11:33:32

问题


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


回答1:


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



回答2:


    **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 "****";
    }

}


来源:https://stackoverflow.com/questions/61663741/how-to-initialize-mongoclient-once-in-spring-boot-and-export-it-to-use-its-metho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!