Issue
I'd like to create a JavaMailSender
bean in Spring 5, reading the properties from a reactive database.
@Bean
public JavaMailSender javaMailSender() {
JavaMailSender javaMailSender = new JavaMailSender();
Settings settings = settingsRepository.findByXXX().block(); //returns Mono<Settings> -> Settings after blocking
//copy stuff from settings to javaMailSender
return javaMailSender;
}
Is there any other way than blocking to do this?
Solution
You should totally avoid using .block()
in Spring-Webflux or anykind of reactive framework. By blocking, you will do nothing else than blocking the current thread, so you will produce an overkill of the application. Instead of blocking you can use functions like .map()
or .flatMap()
and handle the object inside the mono in a reactive manner.
EDIT
@Bean
public Mono<JavaMailSender> javaMailSender() {
return settingsRepository.findByXXX().flatMap(settings -> {
if(something) {
return Mono.just(new JavaMailSender());
} else {
return Mono.error(new RuntimeException());
}
});
}
Answered By - Dina Bogdan
Answer Checked By - David Goodson (JavaFixing Volunteer)