I am trying to upgrade the log4j version to 2.16.0 with the springboot version 2.6.2 .After upgrading My code is failing with the below error while connecting to MongoDB database .Which version of spring-data-mongodb is compatible with the springboot version 2.6.2 .Could anyone suggest which version of Mongodb is the proper version for the below Java code . Any help would be appreciated
Error:(51,27) java: package MongoClientOptions does not exist . My pom.xml as like below
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/>
</parent>
<groupId>com.sample</groupId>
<artifactId>SampleService</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SampleService</name>
<description>Project for Service</description>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<surefire-plugin.version>2.22.0</surefire-plugin.version>
<log4j2.version>2.17.0</log4j2.version>
</properties>
<dependencyManagement>
<dependencies>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>https://repo.spring.io/libs-milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<systemProperties>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.2</version>
<configuration>
<arguments>
<source>1.8</source>
<target>1.8</target>
<uberJar>true</uberJar>
</arguments>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
My Application Java Code :
package com.sample;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
@SpringBootApplication
public class Application implements CommandLineRunner {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
//private String uri;
private String database;
private String host;
private String username;
private String password;
private int port;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
LOG.info("Application Running.......");
}
public @Bean
com.mongodb.MongoClient mongoClient() {
MongoClientOptions.Builder mongoClientOptions = MongoClientOptions.builder().sslInvalidHostNameAllowed(true)
.sslEnabled(true).applicationName("Sample-Service");
try {
KeyStore keystore = KeyStore.getInstance("JKS");
try (InputStream in = new FileInputStream("/mnt/secrets/keystore.jks")) {
keystore.load(in, "password".toCharArray());
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, "password".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
mongoClientOptions.sslContext(sslContext);
} catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
e.printStackTrace();
}
MongoClientOptions mops = mongoClientOptions.build();
MongoCredential mongoCredential = MongoCredential.createCredential(username, database, password.toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), mongoCredential, mops);
return mongoClient;
}
// @Value("${spring.data.mongodb.uri}")
// public void setUri(String uri) {
// this.uri = uri;
// }
public String getDatabase() {
return database;
}
@Value("${spring.data.mongodb.authentication-database}")
public void setDatabase(String database) {
this.database = database;
}
public String getHost() {
return host;
}
@Value("${spring.data.mongodb.host}")
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
@Value("${spring.data.mongodb.username}")
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
@Value("${spring.data.mongodb.password}")
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
@Value("${spring.data.mongodb.port}")
public void setPort(int port) {
this.port = port;
}
}
CodePudding user response:
Your pom.xml
is asking for mongodb-driver-sync 4.2.3. Some of the classes moved or were retired in the 4.x version; for example, com.mongodb.MongoClient
is now com.mongodb.client.MongoClient
. Your code appears to be 3.x API compatible. You will have to spend a few minutes to rework your options setup to be compatible with the new classes. See the API docs https://mongodb.github.io/mongo-java-driver/4.2/apidocs for more.
UPDATED
I took a look and the migration to the new classes is not trivial and I hadn't used non-connection string based material in a long time so I reworked the critical parts of the code above. Note that credential
, sslsettings
, and connectionstring
objects are designed to be built in slightly different ways which can lead to some confusion at first.
import com.mongodb.client.MongoClient; // interface
import com.mongodb.client.MongoClients; // factory
import com.mongodb.MongoClientSettings; // yes, *not* in the .client hierarchy!
import com.mongodb.MongoCredential;
import com.mongodb.ConnectionString;
MongoCredential credentials = MongoCredential.createCredential(
"USER", "ADMIN_DB", "PASSWORD".toCharArray());
String conns = String.format("mongodb://%s:%d/?replicaSet=rs0", "localhost", 27017);
MongoClientSettings.Builder mcsb = MongoClientSettings.builder();
MongoClientSettings mcs = mcsb
.applicationName("Sample-Service")
.credential(credentials)
.applyToSslSettings(sslb ->
sslb.enabled(true)
.invalidHostNameAllowed(true))
.applyConnectionString(new ConnectionString(conns))
.build();
MongoClient client = MongoClients.create(mcs);
CodePudding user response:
I think you should upgrade your dependencies. Please see the version and pom
Please try:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.3.0</version>
</dependency>
<!-- reactive: Do you really need it? -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.0</version>
</dependency>
Suggestion
If you use spring-boot
, and you can try org.springframework.boot:spring-boot-starter-data-mongodb
to auto config.