BAEL-5366 Spring Data MongoDB - Configure Connection (#12544)

* moving SpringBootPersistenceApplication class to its own package

* from com.baeldung to com.baeldung.logging to prevent it from loading
contexts from other applications.

* moving SpringBootPersistenceApplication class to its own package

* from com.baeldung to com.baeldung.logging to prevent it from loading
contexts from other applications.

* Spring Data MongoDB - Configure Connection

Ready for revision.

* fixed tests to reflect article changes

* BAEL-5657

* reverting BAEL-5657

* reverting BAEL-5657
This commit is contained in:
Ulisses Lima 2022-08-26 05:34:07 -03:00 committed by GitHub
parent ec6499d944
commit f8278e0f63
7 changed files with 325 additions and 1 deletions

View File

@ -0,0 +1,31 @@
package com.baeldung.boot.connection.via.builder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.ConnectionString;
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
@EnableMongoRepositories(basePackages = { "com.baeldung.boot.connection.base" })
@SpringBootApplication(scanBasePackages = { "com.baeldung.boot.connection.base" })
public class SpringMongoConnectionViaBuilderApp {
public static void main(String... args) {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaBuilderApp.class);
app.web(WebApplicationType.NONE);
app.run(args);
}
@Bean
public MongoClientSettingsBuilderCustomizer customizer(@Value("${custom.uri}") String uri) {
ConnectionString connection = new ConnectionString(uri);
return settings -> settings.applyConnectionString(connection);
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.boot.connection.via.client;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.client.ListDatabasesIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
@EnableMongoRepositories(basePackages = { "com.baeldung.boot.connection.base" })
@SpringBootApplication(scanBasePackages = { "com.baeldung.boot.connection.base" })
public class SpringMongoConnectionViaClientApp extends AbstractMongoClientConfiguration {
public static void main(String... args) {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaClientApp.class);
app.web(WebApplicationType.NONE);
app.run(args);
}
@Value("${spring.data.mongodb.uri}")
private String uri;
@Value("${spring.data.mongodb.database}")
private String db;
@Override
public MongoClient mongoClient() {
MongoClient client = MongoClients.create(uri);
ListDatabasesIterable<Document> databases = client.listDatabases();
databases.forEach(System.out::println);
return client;
}
@Override
protected String getDatabaseName() {
return db;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.boot.connection.via.factory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClient;
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
@EnableMongoRepositories(basePackages = { "com.baeldung.boot.connection.base" })
@SpringBootApplication(scanBasePackages = { "com.baeldung.boot.connection.base" })
public class SpringMongoConnectionViaFactoryApp {
public static void main(String... args) {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaFactoryApp.class);
app.web(WebApplicationType.NONE);
app.run(args);
}
@Bean
public MongoClientFactoryBean mongo(@Value("${custom.uri}") String uri) throws Exception {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
ConnectionString conn = new ConnectionString(uri);
mongo.setConnectionString(conn);
mongo.setSingleton(false);
MongoClient client = mongo.getObject();
client.listDatabaseNames()
.forEach(System.out::println);
return mongo;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.boot.connection.via.properties;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@PropertySource("classpath:connection.via.properties/app.properties")
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
@EnableMongoRepositories(basePackages = { "com.baeldung.boot.connection.base" })
@SpringBootApplication(scanBasePackages = { "com.baeldung.boot.connection.base" })
public class SpringMongoConnectionViaPropertiesApp {
public static void main(String... args) {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class);
app.web(WebApplicationType.NONE);
app.run(args);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.logging;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -0,0 +1,5 @@
spring.data.mongodb.database=baeldung
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.username=admin
spring.data.mongodb.password=password

View File

@ -0,0 +1,180 @@
package com.baeldung.boot.connection.via.tests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.annotation.DirtiesContext;
import com.baeldung.boot.connection.via.builder.SpringMongoConnectionViaBuilderApp;
import com.baeldung.boot.connection.via.client.SpringMongoConnectionViaClientApp;
import com.baeldung.boot.connection.via.factory.SpringMongoConnectionViaFactoryApp;
import com.baeldung.boot.connection.via.properties.SpringMongoConnectionViaPropertiesApp;
@DirtiesContext
public class MongoConnectionApplicationLiveTest {
private static final String HOST = "localhost";
private static final String PORT = "27017";
private static final String DB = "baeldung";
private static final String USER = "admin";
private static final String PASS = "password";
private void assertInsertSucceeds(ConfigurableApplicationContext context) {
String name = "A";
MongoTemplate mongo = context.getBean(MongoTemplate.class);
Document doc = Document.parse("{\"name\":\"" + name + "\"}");
Document inserted = mongo.insert(doc, "items");
assertNotNull(inserted.get("_id"));
assertEquals(inserted.get("name"), name);
}
@Before
public void clearSystemProperties() {
System.clearProperty("spring.data.mongodb.host");
System.clearProperty("spring.data.mongodb.port");
System.clearProperty("spring.data.mongodb.database");
System.clearProperty("spring.data.mongodb.username");
System.clearProperty("spring.data.mongodb.password");
System.clearProperty("spring.data.mongodb.uri");
}
@Test
public void whenPropertiesConfig_thenInsertSucceeds() {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class);
app.web(WebApplicationType.NONE)
.run();
assertInsertSucceeds(app.context());
}
@Test
public void whenSystemConfig_thenInsertSucceeds() {
System.setProperty("spring.data.mongodb.host", HOST);
System.setProperty("spring.data.mongodb.port", PORT);
System.setProperty("spring.data.mongodb.database", DB);
System.setProperty("spring.data.mongodb.username", USER);
System.setProperty("spring.data.mongodb.password", PASS);
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class);
app.web(WebApplicationType.NONE)
.run();
assertInsertSucceeds(app.context());
}
@Test
public void givenPrecedence_whenSystemConfig_thenInsertSucceeds() {
System.setProperty("spring.data.mongodb.host", HOST);
System.setProperty("spring.data.mongodb.port", PORT);
System.setProperty("spring.data.mongodb.database", DB);
System.setProperty("spring.data.mongodb.username", USER);
System.setProperty("spring.data.mongodb.password", PASS);
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class)
.properties(
"spring.data.mongodb.host=oldValue",
"spring.data.mongodb.port=oldValue",
"spring.data.mongodb.database=oldValue",
"spring.data.mongodb.username=oldValue",
"spring.data.mongodb.password=oldValue"
);
app.web(WebApplicationType.NONE)
.run();
assertInsertSucceeds(app.context());
}
@Test
public void givenPrecedence_whenApplicationArgs_thenInsertSucceeds() {
System.setProperty("spring.data.mongodb.host", "incorrect");
System.setProperty("spring.data.mongodb.port", "incorrect");
System.setProperty("spring.data.mongodb.database", "incorrect");
System.setProperty("spring.data.mongodb.username", "incorrect");
System.setProperty("spring.data.mongodb.password", "incorrect");
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class);
app.web(WebApplicationType.NONE)
.run(
"--spring.data.mongodb.host=" + HOST,
"--spring.data.mongodb.port=" + PORT,
"--spring.data.mongodb.database=" + DB,
"--spring.data.mongodb.username=" + USER,
"--spring.data.mongodb.password=" + PASS
);
assertInsertSucceeds(app.context());
}
@Test
public void givenConnectionUri_whenAlsoIncludingIndividualParameters_thenInvalidConfig() {
System.setProperty(
"spring.data.mongodb.uri",
"mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB
);
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class)
.web(WebApplicationType.NONE)
.properties(
"spring.data.mongodb.host=" + HOST,
"spring.data.mongodb.port=" + PORT,
"spring.data.mongodb.username=" + USER,
"spring.data.mongodb.password=" + PASS
);
BeanCreationException e = assertThrows(BeanCreationException.class, () -> {
app.run();
});
Throwable rootCause = e.getRootCause();
assertTrue(rootCause instanceof IllegalStateException);
assertThat(rootCause.getMessage()
.contains("Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified"));
}
@Test
public void whenClientConfig_thenInsertSucceeds() {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaClientApp.class);
app.web(WebApplicationType.NONE)
.run(
"--spring.data.mongodb.uri=mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB,
"--spring.data.mongodb.database=" + DB
);
assertInsertSucceeds(app.context());
}
@Test
public void whenFactoryConfig_thenInsertSucceeds() {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaFactoryApp.class);
app.web(WebApplicationType.NONE)
.run(
"--custom.uri=mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB
);
assertInsertSucceeds(app.context());
}
@Test
public void whenBuilderConfig_thenInsertSucceeds() {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaBuilderApp.class);
app.web(WebApplicationType.NONE)
.run(
"--custom.uri=mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB
);
assertInsertSucceeds(app.context());
}
}