Mongo-backed sessions¶
Deprecated. Spring Session 4.0 removed its MongoDB module, so
spring-session-data-mongodbis no longer part of the Spring Session BOM and has no 4.x release — see spring-boot#47662 ("Remove support for Spring Session Data MongoDB", closed in commitc477d3b). The last release from the Spring Session project is3.5.7, which is what the legacy sample pins. The maintained replacement isorg.mongodb:mongodb-spring-session, published by the MongoDB team for Spring Session 4.0+, with the classes relocated toorg.mongodb.spring.session.*.
The spring-session-data-mongodb module stores sessions in MongoDB through the reactive Mongo driver — a natural choice when your application already uses Spring Data Mongo.
Step 1: add the dependencies¶
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-mongodb</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-reactivestreams</artifactId>
</dependency>
Step 2: configure the Mongo connection¶
@Configuration
public class MongoConfig extends AbstractReactiveMongoConfiguration {
@Value("${mongo.uri}")
String mongoUri;
@Override
public MongoClient reactiveMongoClient() {
return MongoClients.create(mongoUri);
}
@Override
protected String getDatabaseName() {
return "blog";
}
}
With the connection property set in application.properties:
Start a MongoDB server for local development:
Step 3: enable Mongo web session¶
@EnableMongoWebSession registers a reactive session repository backed by MongoDB automatically. The controller and template code is identical to the in-memory example.
Verify¶
Start the application, submit the attribute form at http://localhost:8080, and inspect the blog database — the sessions live in a dedicated collection with the attributes and a TTL index for expiry.
You can explore the complete codes in spring-reactive-sample/legacy/session-data-mongo.