Caused by: java.lang.ClassNotFoundException: com.mongodb.internal.connection.DefaultClusterFactory

I’m working on a upgrade programe.

Facing issue with connection string

public static void main(String[] args) throws Throwable {
        MongoCredential credential = MongoCredential.createCredential("user", "dbName", "password".toCharArray());
        Block<ClusterSettings.Builder> localhost = builder -> builder.hosts(singletonList(new ServerAddress("host.mongodb.net", 27017)));
        MongoClientSettings settings = MongoClientSettings.builder()
                .applyToClusterSettings(localhost)
                .credential(credential)
                .build();
        MongoClient client = MongoClients.create(settings);
        MongoCollection<Document> col = client.getDatabase("test").getCollection("col");
        System.out.println(col.countDocuments());

}

error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/internal/connection/DefaultClusterFactory
	at com.mongodb.client.internal.MongoClientImpl.createCluster(MongoClientImpl.java:208)
	at com.mongodb.client.internal.MongoClientImpl.<init>(MongoClientImpl.java:63)
	at com.mongodb.client.MongoClients.create(MongoClients.java:108)
	at com.mongodb.client.MongoClients.create(MongoClients.java:50)
	at ServiceApplication.main(ServiceApplication.java:48)
Caused by: java.lang.ClassNotFoundException: com.mongodb.internal.connection.DefaultClusterFactory
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
	... 5 more

Process finished with exit code 1

the other piece of code that I tried is :
@Bean
public MongoDatabaseFactory mongoDatabaseFactory() throws NoSuchAlgorithmException, KeyManagementException {

    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance(InmarsatConstants.SSL_PROTOCOL);

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[]{new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[0];
            }
        }}, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        throw new NoSuchAlgorithmException(e);
    } catch (KeyManagementException e) {
        throw new KeyManagementException(e);
    }
    MongoCredential credential = MongoCredential.createCredential(mongoDbUserName,mongoDbName,mongoDbPassword.toCharArray());
    MongoClient mongoClient = MongoClients.create(
            MongoClientSettings.builder()
                    .applyToClusterSettings(builder ->
                            builder.hosts(Arrays.asList(new ServerAddress("mongodb://"+mongoDbCLientHostName, 27017))))
                    .credential(credential)
                    .build());

    return new SimpleMongoClientDatabaseFactory(mongoClient,mongoDbName);
}

@Bean
public MongoTemplate mongoTemplate() throws KeyManagementException, NoSuchAlgorithmException {
    return new MongoTemplate(mongoDatabaseFactory());
}
public @Bean
com.mongodb.client.MongoClient mongoClient() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance(InmarsatConstants.SSL_PROTOCOL);

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[]{new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {


            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[0];
            }
        }}, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        throw new NoSuchAlgorithmException(e);
    } catch (KeyManagementException e) {
        throw new KeyManagementException(e);
    }


    CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
    CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);


    MongoCredential credential = MongoCredential.createCredential(mongoDbUserName,mongoDbName,mongoDbPassword.toCharArray());
    MongoClient mongoClient = MongoClients.create(
            MongoClientSettings.builder()
                    .applyToClusterSettings(builder ->
                            builder.hosts(Arrays.asList(new ServerAddress("mongodb://"+mongoDbCLientHostName, 27017))))
                    .credential(credential).codecRegistry(codecRegistry)
                    .build());
    return mongoClient;

}

error:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDatabaseFactory]: Factory method 'mongoDatabaseFactory' threw exception; nested exception is com.mongodb.MongoException: host and port should be specified in host:port format
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
	... 24 common frames omitted
Caused by: com.mongodb.MongoException: host and port should be specified in host:port format
	at com.mongodb.ServerAddress.<init>(ServerAddress.java:125)
	at ServiceApplication.lambda$mongoDatabaseFactory$0(ServiceApplication.java:96)
	at com.mongodb.MongoClientSettings$Builder.applyToClusterSettings(MongoClientSettings.java:230)
	at ServiceApplication.mongoDatabaseFactory(ServiceApplication.java:95)
	at ServiceApplication$$EnhancerBySpringCGLIB$$c3b4fc1b.CGLIB$mongoDatabaseFactory$0(<generated>)
	at ServiceApplication$$EnhancerBySpringCGLIB$$c3b4fc1b$$FastClassBySpringCGLIB$$22498f2e.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
	at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)

Dependencies used for both the cases:

<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>3.2.3</version>
        </dependency>
<dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>4.2.3</version>
        </dependency>

Hi Team,

I also referred GitHub - mongodb-developer/java-quick-start: This repository contains code samples for the Java Quick Start blog post series but no luck

Hi Team,

The major issue is with connecting string. Unable to create MongoClient.

Mentioning again, need to upgrade Java code compatible to Mongodb 4.4. Hence using dependency

Dependencies used for both the cases:

org.springframework.data spring-data-mongodb 3.2.3 org.mongodb mongodb-driver-sync 4.2.3
1 Like

I’m using mongodb with spring framework and ran into a similar issue. See stack trace below. Using the dependency versions 3.2.3 and 4.2.3 fixed my problem, thank you!

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NoClassDefFoundError: com/mongodb/internal/connection/InternalConnectionPoolSettings
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.18.jar:5.3.18]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.18.jar:5.3.18]
	... 99 common frames omitted
Caused by: java.lang.NoClassDefFoundError: com/mongodb/internal/connection/InternalConnectionPoolSettings
	at com.mongodb.client.internal.MongoClientImpl.createCluster(MongoClientImpl.java:223) ~[mongodb-driver-sync-4.6.0.jar:na]
	at com.mongodb.client.internal.MongoClientImpl.<init>(MongoClientImpl.java:70) ~[mongodb-driver-sync-4.6.0.jar:na]