Prefer Java configuration over XML.

Closes #4186
This commit is contained in:
Mark Paluch
2022-09-28 15:29:10 +02:00
parent e9818fe11a
commit 2d2f67cc93
9 changed files with 162 additions and 134 deletions

View File

@@ -3,7 +3,8 @@ Mark Pollack; Thomas Risberg; Oliver Gierke; Costin Leau; Jon Brisbin; Thomas Da
:revnumber: {version}
:revdate: {localdate}
ifdef::backend-epub3[:front-cover-image: image:epub-cover.png[Front Cover,1050,1600]]
:spring-data-commons-docs: ../../../../../spring-data-commons/src/main/asciidoc
:spring-data-commons-docs: ../../../../spring-data-commons/src/main/asciidoc
:store: Mongo
(C) 2008-2022 The original authors.

View File

@@ -3,9 +3,10 @@
MongoDB supports storing binary files inside its filesystem, GridFS. Spring Data MongoDB provides a `GridFsOperations` interface as well as the corresponding implementation, `GridFsTemplate`, to let you interact with the filesystem. You can set up a `GridFsTemplate` instance by handing it a `MongoDatabaseFactory` as well as a `MongoConverter`, as the following example shows:
.JavaConfig setup for a GridFsTemplate
====
[source,java]
.Java
[source,java,role="primary"]
----
class GridFsConfiguration extends AbstractMongoClientConfiguration {
@@ -17,13 +18,9 @@ class GridFsConfiguration extends AbstractMongoClientConfiguration {
}
}
----
====
The corresponding XML configuration follows:
.XML configuration for a GridFsTemplate
====
[source,xml]
.XML
[source,xml,role="secondary"]
----
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

View File

@@ -266,11 +266,11 @@ calling `get()` before the actual conversion
Unless explicitly configured, an instance of `MappingMongoConverter` is created by default when you create a `MongoTemplate`. You can create your own instance of the `MappingMongoConverter`. Doing so lets you dictate where in the classpath your domain classes can be found, so that Spring Data MongoDB can extract metadata and construct indexes. Also, by creating your own instance, you can register Spring converters to map specific classes to and from the database.
You can configure the `MappingMongoConverter` as well as `com.mongodb.client.MongoClient` and MongoTemplate by using either Java-based or XML-based metadata. The following example uses Spring's Java-based configuration:
You can configure the `MappingMongoConverter` as well as `com.mongodb.client.MongoClient` and MongoTemplate by using either Java-based or XML-based metadata. The following example shows the configuration:
.@Configuration class to configure MongoDB mapping support
====
[source,java]
.Java
[source,java,role="primary"]
----
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
@@ -299,24 +299,11 @@ public class MongoConfig extends AbstractMongoClientConfiguration {
return new LoggingEventListener<MongoMappingEvent>();
}
}
----
<1> The mapping base package defines the root path used to scan for entities used to pre initialize the `MappingContext`. By default the configuration classes package is used.
<2> Configure additional custom converters for specific domain types that replace the default mapping procedure for those types with your custom implementation.
====
`AbstractMongoClientConfiguration` requires you to implement methods that define a `com.mongodb.client.MongoClient` as well as provide a database name. `AbstractMongoClientConfiguration` also has a method named `getMappingBasePackage(…)` that you can override to tell the converter where to scan for classes annotated with the `@Document` annotation.
You can add additional converters to the converter by overriding the `customConversionsConfiguration` method.
MongoDB's native JSR-310 support can be enabled through `MongoConverterConfigurationAdapter.useNativeDriverJavaTimeCodecs()`.
Also shown in the preceding example is a `LoggingEventListener`, which logs `MongoMappingEvent` instances that are posted onto Spring's `ApplicationContextEvent` infrastructure.
NOTE: `AbstractMongoClientConfiguration` creates a `MongoTemplate` instance and registers it with the container under the name `mongoTemplate`.
Spring's MongoDB namespace lets you enable mapping functionality in XML, as the following example shows:
.XML schema to configure MongoDB mapping support
====
[source,xml]
.XML
[source,xml,role="secondary"]
----
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
@@ -353,8 +340,19 @@ Spring's MongoDB namespace lets you enable mapping functionality in XML, as the
</beans>
----
<1> The mapping base package defines the root path used to scan for entities used to pre initialize the `MappingContext`. By default the configuration classes package is used.
<2> Configure additional custom converters for specific domain types that replace the default mapping procedure for those types with your custom implementation.
====
`AbstractMongoClientConfiguration` requires you to implement methods that define a `com.mongodb.client.MongoClient` as well as provide a database name. `AbstractMongoClientConfiguration` also has a method named `getMappingBasePackage(…)` that you can override to tell the converter where to scan for classes annotated with the `@Document` annotation.
You can add additional converters to the converter by overriding the `customConversionsConfiguration` method.
MongoDB's native JSR-310 support can be enabled through `MongoConverterConfigurationAdapter.useNativeDriverJavaTimeCodecs()`.
Also shown in the preceding example is a `LoggingEventListener`, which logs `MongoMappingEvent` instances that are posted onto Spring's `ApplicationContextEvent` infrastructure.
NOTE: `AbstractMongoClientConfiguration` creates a `MongoTemplate` instance and registers it with the container under the name `mongoTemplate`.
The `base-package` property tells it where to scan for classes annotated with the `@org.springframework.data.mongodb.core.mapping.Document` annotation.
[[mapping-usage]]
@@ -607,7 +605,7 @@ The mapping subsystem allows the customization of the object construction by ann
* If a parameter is annotated with the `@Value` annotation, the given expression is evaluated and the result is used as the parameter value.
* If the Java type has a property whose name matches the given field of the input document, then it's property information is used to select the appropriate constructor parameter to pass the input field value to. This works only if the parameter name information is present in the java `.class` files which can be achieved by compiling the source with debug information or using the new `-parameters` command-line switch for javac in Java 8.
* Otherwise a `MappingException` will be thrown indicating that the given constructor parameter could not be bound.
* Otherwise, a `MappingException` will be thrown indicating that the given constructor parameter could not be bound.
[source,java]
----

View File

@@ -1,11 +1,11 @@
[[mongo.auditing]]
== General Auditing Configuration for MongoDB
Since Spring Data MongoDB 1.4, auditing can be enabled by annotating a configuration class with the `@EnableMongoAuditing` annotation, as the followign example shows:
Since Spring Data MongoDB 1.4, auditing can be enabled by annotating a configuration class with the `@EnableMongoAuditing` annotation, as the following example shows:
.Activating auditing using JavaConfig
====
[source,java]
.Java
[source,java,role="primary"]
----
@Configuration
@EnableMongoAuditing
@@ -17,19 +17,16 @@ class Config {
}
}
----
====
If you expose a bean of type `AuditorAware` to the `ApplicationContext`, the auditing infrastructure picks it up automatically and uses it to determine the current user to be set on domain types. If you have multiple implementations registered in the `ApplicationContext`, you can select the one to be used by explicitly setting the `auditorAwareRef` attribute of `@EnableMongoAuditing`.
To activate auditing functionality via XML, add the Spring Data Mongo `auditing` namespace element to your configuration, as the following example shows:
.Activating auditing by using XML configuration
====
[source,xml]
.XML
[source,xml,role="secondary"]
----
<mongo:auditing mapping-context-ref="customMappingContext" auditor-aware-ref="yourAuditorAwareImpl"/>
----
====
If you expose a bean of type `AuditorAware` to the `ApplicationContext`, the auditing infrastructure picks it up automatically and uses it to determine the current user to be set on domain types. If you have multiple implementations registered in the `ApplicationContext`, you can select the one to be used by explicitly setting the `auditorAwareRef` attribute of `@EnableMongoAuditing`.
To enable auditing, leveraging a reactive programming model, use the `@EnableReactiveMongoAuditing` annotation. +
If you expose a bean of type `ReactiveAuditorAware` to the `ApplicationContext`, the auditing infrastructure picks it up automatically and uses it to determine the current user to be set on domain types. If you have multiple implementations registered in the `ApplicationContext`, you can select the one to be used by explicitly setting the `auditorAwareRef` attribute of `@EnableReactiveMongoAuditing`.

View File

@@ -82,7 +82,7 @@ Use the `@Meta` annotation to set those options via `maxExecutionTimeMs`, `comme
[source,java]
----
public interface PersonRepository extends CrudReppsitory<Person, String> {
interface PersonRepository extends CrudReppsitory<Person, String> {
@Meta(allowDiskUse = true)
@Aggregation("{ $group: { _id : $lastname, names : { $addToSet : $firstname } } }")
@@ -99,7 +99,7 @@ Or use `@Meta` to create your own annotation as shown in the sample below.
@Meta(allowDiskUse = true)
@interface AllowDiskUse { }
public interface PersonRepository extends CrudReppsitory<Person, String> {
interface PersonRepository extends CrudReppsitory<Person, String> {
@AllowDiskUse
@Aggregation("{ $group: { _id : $lastname, names : { $addToSet : $firstname } } }")

View File

@@ -51,14 +51,14 @@ Right now this interface serves only to provide type information, but we can add
To start using the repository, use the `@EnableMongoRepositories` annotation.
That annotation carries the same attributes as the namespace element.
If no base package is configured, the infrastructure scans the package of the annotated configuration class.
The following example shows how to use Java configuration for a repository:
The following example shows how to configuration your application to use MongoDB repositories:
.Java configuration for repositories
====
[source,java]
.Java
[source,java,role="primary"]
----
@Configuration
@EnableMongoRepositories
@EnableMongoRepositories("com.acme.*.repositories")
class ApplicationConfig extends AbstractMongoClientConfiguration {
@Override
@@ -68,17 +68,13 @@ class ApplicationConfig extends AbstractMongoClientConfiguration {
@Override
protected String getMappingBasePackage() {
return "com.oreilly.springdata.mongodb";
return "com.acme.*.repositories";
}
}
----
====
If you would rather go with XML based configuration add the following content:
.General MongoDB repository Spring XML configuration
====
[source,xml]
.XML
[source,xml,role="secondary"]
----
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
@@ -113,14 +109,14 @@ Consequently, accessing the second page of `Person` objects at a page size of 10
====
[source,java]
----
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration
public class PersonRepositoryTests {
class PersonRepositoryTests {
@Autowired PersonRepository repository;
@Test
public void readsFirstPageCorrectly() {
void readsFirstPageCorrectly() {
Page<Person> persons = repository.findAll(PageRequest.of(0, 10));
assertThat(persons.isFirstPage()).isTrue();

View File

@@ -321,7 +321,8 @@ The code in bold highlights the use of `SimpleMongoClientDbFactory` and is the o
NOTE: Use `SimpleMongoClientDbFactory` when choosing `com.mongodb.client.MongoClient` as the entrypoint of choice.
[[mongo.mongo-db-factory-java]]
=== Registering a `MongoDatabaseFactory` Instance by Using Java-based Metadata
[[mongo.mongo-db-factory.config]]
=== Registering a `MongoDatabaseFactory`
To register a `MongoDatabaseFactory` instance with the container, you write code much like what was highlighted in the previous code listing. The following listing shows a simple example:
@@ -330,7 +331,8 @@ To register a `MongoDatabaseFactory` instance with the container, you write code
@Configuration
public class MongoConfiguration {
public @Bean MongoDatabaseFactory mongoDatabaseFactory() {
@Bean
public MongoDatabaseFactory mongoDatabaseFactory() {
return new SimpleMongoClientDatabaseFactory(MongoClients.create(), "database");
}
}
@@ -338,7 +340,9 @@ public class MongoConfiguration {
MongoDB Server generation 3 changed the authentication model when connecting to the DB. Therefore, some of the configuration options available for authentication are no longer valid. You should use the `MongoClient`-specific options for setting credentials through `MongoCredential` to provide authentication data, as shown in the following example:
[source,java]
====
.Java
[source,java,role="primary"]
----
@Configuration
public class ApplicationContextEventTestsAppConfig extends AbstractMongoClientConfiguration {
@@ -351,35 +355,70 @@ public class ApplicationContextEventTestsAppConfig extends AbstractMongoClientCo
@Override
protected void configureClientSettings(Builder builder) {
builder
.credential(MongoCredential.createCredential("name", "db", "pwd".toCharArray()))
.applyToClusterSettings(settings -> {
settings.hosts(singletonList(new ServerAddress("127.0.0.1", 27017)));
});
builder
.credential(MongoCredential.createCredential("name", "db", "pwd".toCharArray()))
.applyToClusterSettings(settings -> {
settings.hosts(singletonList(new ServerAddress("127.0.0.1", 27017)));
});
}
}
----
In order to use authentication with XML-based configuration, use the `credential` attribute on the `<mongo-client>` element.
.XML
[source,xml,role="secondary"]
----
<mongo:db-factory dbname="database" />
----
====
NOTE: Username and password credentials used in XML-based configuration must be URL-encoded when these contain reserved characters, such as `:`, `%`, `@`, or `,`.
The following example shows encoded credentials:
`m0ng0@dmin:mo_res:bw6},Qsdxx@admin@database` -> `m0ng0%40dmin:mo_res%3Abw6%7D%2CQsdxx%40admin@database`
See https://tools.ietf.org/html/rfc3986#section-2.2[section 2.2 of RFC 3986] for further details.
[[mongo.mongo-db-factory-xml]]
=== Registering a `MongoDatabaseFactory` Instance by Using XML-based Metadata
If you need to configure additional options on the `com.mongodb.client.MongoClient` instance that is used to create a `SimpleMongoClientDbFactory`, you can refer to an existing bean as shown in the following example. To show another common usage pattern, the following listing shows the use of a property placeholder, which lets you parametrize the configuration and the creation of a `MongoTemplate`:
The `mongo` namespace provides a convenient way to create a `SimpleMongoClientDbFactory`, as compared to using the `<beans/>` namespace, as shown in the following example:
[source,xml]
====
.Java
[source,java,role="primary"]
----
<mongo:db-factory dbname="database">
@Configuration
@PropertySource("classpath:/com/myapp/mongodb/config/mongo.properties")
public class ApplicationContextEventTestsAppConfig extends AbstractMongoClientConfiguration {
@Autowired
Environment env;
@Override
public String getDatabaseName() {
return "database";
}
@Override
protected void configureClientSettings(Builder builder) {
builder.applyToClusterSettings(settings -> {
settings.hosts(singletonList(
new ServerAddress(env.getProperty("mongo.host"), env.getProperty("mongo.port", Integer.class))));
});
builder.applyToConnectionPoolSettings(settings -> {
settings.maxConnectionLifeTime(env.getProperty("mongo.pool-max-life-time", Integer.class), TimeUnit.MILLISECONDS)
.minSize(env.getProperty("mongo.pool-min-size", Integer.class))
.maxSize(env.getProperty("mongo.pool-max-size", Integer.class))
.maintenanceFrequency(10, TimeUnit.MILLISECONDS)
.maintenanceInitialDelay(11, TimeUnit.MILLISECONDS)
.maxConnectionIdleTime(30, TimeUnit.SECONDS)
.maxWaitTime(15, TimeUnit.MILLISECONDS);
});
}
}
----
If you need to configure additional options on the `com.mongodb.client.MongoClient` instance that is used to create a `SimpleMongoClientDbFactory`, you can refer to an existing bean by using the `mongo-ref` attribute as shown in the following example. To show another common usage pattern, the following listing shows the use of a property placeholder, which lets you parametrize the configuration and the creation of a `MongoTemplate`:
[source,xml]
.XML
[source,xml,role="secondary"]
----
<context:property-placeholder location="classpath:/com/myapp/mongodb/config/mongo.properties"/>
@@ -387,10 +426,10 @@ If you need to configure additional options on the `com.mongodb.client.MongoClie
<mongo:client-settings connection-pool-max-connection-life-time="${mongo.pool-max-life-time}"
connection-pool-min-size="${mongo.pool-min-size}"
connection-pool-max-size="${mongo.pool-max-size}"
connection-pool-maintenance-frequency="10"
connection-pool-maintenance-initial-delay="11"
connection-pool-max-connection-idle-time="30"
connection-pool-max-wait-time="15" />
connection-pool-maintenance-frequency="10"
connection-pool-maintenance-initial-delay="11"
connection-pool-max-connection-idle-time="30"
connection-pool-max-wait-time="15" />
</mongo:mongo-client>
<mongo:db-factory dbname="database" mongo-ref="mongoClient"/>
@@ -399,6 +438,7 @@ If you need to configure additional options on the `com.mongodb.client.MongoClie
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
----
====
[[mongo-template]]
== Introduction to `MongoTemplate`
@@ -424,24 +464,38 @@ The next section contains an example of how to work with the `MongoTemplate` in
[[mongo-template.instantiating]]
=== Instantiating `MongoTemplate`
You can use Java to create and register an instance of `MongoTemplate`, as the following example shows:
You can use the following configuration to create and register an instance of `MongoTemplate`, as the following example shows:
.Registering a `com.mongodb.client.MongoClient` object and enabling Spring's exception translation support
====
[source,java]
.Java
[source,java,role="primary"]
----
@Configuration
public class AppConfig {
class AppConfig {
public @Bean MongoClient mongoClient() {
@Bean
MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost:27017");
}
public @Bean MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "mydatabase");
@Bean
MongoTemplate mongoTemplate(MongoClient mongoClient) {
return new MongoTemplate(mongoClient, "geospatial");
}
}
----
.XML
[source,xml,role="secondary"]
----
<mongo:mongo-client host="localhost" port="27017"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoClient"/>
<constructor-arg name="databaseName" value="geospatial"/>
</bean>
----
====
There are several overloaded constructors of `MongoTemplate`:
@@ -450,17 +504,6 @@ There are several overloaded constructors of `MongoTemplate`:
* `MongoTemplate(MongoDatabaseFactory mongoDbFactory)`: Takes a MongoDbFactory object that encapsulated the `MongoClient` object, database name, and username and password.
* `MongoTemplate(MongoDatabaseFactory mongoDbFactory, MongoConverter mongoConverter)`: Adds a `MongoConverter` to use for mapping.
You can also configure a MongoTemplate by using Spring's XML <beans/> schema, as the following example shows:
[source,xml]
----
<mongo:mongo-client host="localhost" port="27017"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoClient"/>
<constructor-arg name="databaseName" value="geospatial"/>
</bean>
----
Other optional properties that you might like to set when creating a `MongoTemplate` are the default `WriteResultCheckingPolicy`, `WriteConcern`, and `ReadPreference` properties.
@@ -677,13 +720,13 @@ To achieve that, the `MappingMongoConverter` uses a `MongoTypeMapper` abstractio
====
[source,java]
----
public class Sample {
class Sample {
Contact value;
}
public abstract class Contact { … }
abstract class Contact { … }
public class Person extends Contact { … }
class Person extends Contact { … }
Sample sample = new Sample();
sample.value = new Person();
@@ -725,7 +768,7 @@ By default, the configuration class scans the base package for potential candida
[source,java]
----
@Configuration
public class AppConfig extends AbstractMongoClientConfiguration {
class AppConfig extends AbstractMongoClientConfiguration {
@Override
protected Set<Class<?>> getInitialEntitySet() {
@@ -741,8 +784,6 @@ public class AppConfig extends AbstractMongoClientConfiguration {
The following example shows how to configure a custom `MongoTypeMapper` in `MappingMongoConverter`:
.Configuring a custom `MongoTypeMapper` with Spring Java Config
====
[source,java]
----
class CustomMongoTypeMapper extends DefaultMongoTypeMapper {
@@ -750,8 +791,10 @@ class CustomMongoTypeMapper extends DefaultMongoTypeMapper {
}
----
[source,java]
.Configuring a custom `MongoTypeMapper`
====
.Java
[source,java,role="primary"]
----
@Configuration
class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
@@ -763,7 +806,8 @@ class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
@Bean
@Override
public MappingMongoConverter mappingMongoConverter() throws Exception {
public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory databaseFactory,
MongoCustomConversions customConversions, MongoMappingContext mappingContext) {
MappingMongoConverter mmc = super.mappingMongoConverter();
mmc.setTypeMapper(customTypeMapper());
return mmc;
@@ -775,21 +819,18 @@ class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
}
}
----
.XML
[source,xml,role="secondary"]
----
<mongo:mapping-converter type-mapper-ref="customMongoTypeMapper"/>
<bean name="customMongoTypeMapper" class="com.acme.CustomMongoTypeMapper"/>
----
====
Note that the preceding example extends the `AbstractMongoClientConfiguration` class and overrides the bean definition of the `MappingMongoConverter` where we configured our custom `MongoTypeMapper`.
The following example shows how to use XML to configure a custom `MongoTypeMapper`:
.Configuring a custom `MongoTypeMapper` with XML
====
[source,xml]
----
<mongo:mapping-converter type-mapper-ref="customMongoTypeMapper"/>
<bean name="customMongoTypeMapper" class="com.bubu.mongo.CustomMongoTypeMapper"/>
----
====
[[mongo-template.save-insert]]
=== Methods for Saving and Inserting Documents

View File

@@ -110,7 +110,9 @@ Because our domain repository extends `ReactiveSortingRepository`, it provides y
====
[source,java]
----
public class PersonRepositoryTests {
@ExtendWith(SpringExtension.class)
@ContextConfiguration
class PersonRepositoryTests {
@Autowired ReactivePersonRepository repository;
@@ -162,7 +164,7 @@ The following example shows how to define a `near` query that finds all persons
====
[source,java]
----
public interface PersonRepository extends ReactiveMongoRepository<Person, String> {
interface PersonRepository extends ReactiveMongoRepository<Person, String> {
// { 'location' : { '$near' : [point.x, point.y], '$maxDistance' : distance}}
Flux<Person> findByLocationNear(Point location, Distance distance);
@@ -197,7 +199,7 @@ Spring Data MongoDB supports geo-near queries, as the following example shows:
[source,java]
----
public interface PersonRepository extends ReactiveMongoRepository<Person, String> {
interface PersonRepository extends ReactiveMongoRepository<Person, String> {
// {'geoNear' : 'location', 'near' : [x, y] }
Flux<GeoResult<Person>> findByLocationNear(Point location);
@@ -253,7 +255,7 @@ You can use the generated `Predicate` class by using the `ReactiveQuerydslPredic
====
[source,java]
----
public interface ReactiveQuerydslPredicateExecutor<T> {
interface ReactiveQuerydslPredicateExecutor<T> {
Mono<T> findOne(Predicate predicate);
@@ -278,7 +280,7 @@ To use this in your repository implementation, add it to the list of repository
====
[source,java]
----
public interface PersonRepository extends ReactiveMongoRepository<Person, String>, ReactiveQuerydslPredicateExecutor<Person> {
interface PersonRepository extends ReactiveMongoRepository<Person, String>, ReactiveQuerydslPredicateExecutor<Person> {
// additional query methods go here
}

View File

@@ -166,21 +166,14 @@ Please refer to <<mapping.index-creation>> on how to create indexes programmatic
.Enable Auto Index Creation
====
.XML Namespace
[source,xml]
----
<mongo:mapping-converter auto-index-creation="true" /> <1>
----
.Java Config
[source,java]
.Java
[source,java,role="primary"]
----
@Configuration
public class Config extends AbstractMongoClientConfiguration {
@Override
protected boolean autoIndexCreation() { <2>
protected boolean autoIndexCreation() {
return true;
}
@@ -188,22 +181,25 @@ public class Config extends AbstractMongoClientConfiguration {
}
----
.XML
[source,xml,role="secondary"]
----
<mongo:mapping-converter auto-index-creation="true" />
----
.Programmatic
[source,java]
[source,java,role="secondary"]
----
MongoDatabaseFactory dbFactory = new SimpleMongoClientDatabaseFactory(...);
DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(dbFactory);
MongoMappingContext mappingContext = new MongoMappingContext();
mappingContext.setAutoIndexCreation(true); <3>
mappingContext.setAutoIndexCreation(true);
// ...
mappingContext.afterPropertiesSet();
MongoTemplate template = new MongoTemplate(dbFactory, new MappingMongoConverter(dbRefResolver, mappingContext));
----
<1> Use the XML namespace attribute `auto-index-creation` on `mapping-converter`.
<2> Override `autoIndexCreation` via `AbstractMongoClientConfiguration` or `AbstractReactiveMongoClientConfiguration`.
<3> Set the flag on `MongoMappingContext`.
====
=== UUID Types