Search⌘ K
AI Features

Loading Test Data

Explore the process of loading test data in a Spring Boot reactive application. Understand how to use reactive and blocking repositories, the risks of blocking the event loop during startup, and how to apply MongoTemplate for safe data initialization. This lesson helps you manage test data loading effectively while maintaining reactive programming principles.

Let’s use the repository we just created to load some test data.

Using ItemRepository

If we wanted to grab a copy of our delightful ItemRepository, we’d probably write something like this:

Java
itemRepository.save(new Item("Alf alarm clock", 19.99))

See the problem?

The ReactiveCrudRepository.save() method returns a Mono<T>. In this case, it’s Mono<Item>. Remember, a Mono Reactor type doesn’t actually do anything until we subscribe.

In short, the code above does absolutely nothing. To actually get things moving, we must do this:

Java
itemRepository
.save(new Item("Alf alarm clock", 19.99))
.subscribe()

Keep in mind that there’s still a problem with this, at least during startup. When Netty is launched, the risk of a subscriber causing the startup thread to deadlock its event loop is very real.

Using a nonreactive CRUD repository

When attempting to do something during the startup of our application, the recommendation is to use a blocking version of Spring Data MongoDB!

Because this is about application startup, and focused on test configuration, it’s okay to allow a little bit of blocking code. That’s as long as it doesn’t escape into production!

The only question is, what are we blocking? The repository we defined earlier extends ReactiveCrudRepository. We can create a counterpart repository.

Java
interface BlockingItemRepository extends CrudRepository<Item, String> {
}
Blocking repository definition.

This repository definition is identical to what we created earlier, except that it extends CrudRepository, a blocking ...