Home > database >  Putting Spring WebFlux Publisher inside Model, good or bad practice?
Putting Spring WebFlux Publisher inside Model, good or bad practice?

Time:11-10

I'm working on a code audit on a SpringBoot Application with Spring WebFlux and the team is putting Publisher directly inside the Model and then resolve the view.

I'm wondering if it is a good or bad practice because it seems to be working but in that case, which component is in charge of executing the Publisher ?

I think that it's the ViewResolver and it should not be its job. What do you think ?

Moreover, if the Publisher is not executed by the Controller, the classes annotated by @ControllerAdvice such like ExceptionHandler won't work if these Publisher return an error, right ?

CodePudding user response:

Doesn't come as a shock to me. Actually seems to be a good trade off between complexity and efficiency when the Publisher is handling complex stuff.

It has the advantage of executing the Publisher only if and when needed. Although it might be a problem if the ModelMap handler does not have the capacity to use it properly. As for the exceptional cases, maybe you do not want it to be executed and just printed, thus failing faster.

As for the question about what is executing the Publisher, a specific ViewResolver can be used as it is the component responsible for the "rendering". IMHO that's it's job. I do not know if a standard ViewResolver can be used for detecting values vs publishers and handle those automagically, yet this seems completely doable and efficient.

CodePudding user response:

Extract of the documentation of Spring WebFlux :

Spring WebFlux, unlike Spring MVC, explicitly supports reactive types in the model (for example, Mono or io.reactivex.Single). Such asynchronous model attributes can be transparently resolved (and the model updated) to their actual values at the time of @RequestMapping invocation, provided a @ModelAttribute argument is declared without a wrapper, as the following example shows:

@ModelAttribute
public void addAccount(@RequestParam String number) {
    Mono<Account> accountMono = accountRepository.findAccount(number);
    model.addAttribute("account", accountMono);
}

@PostMapping("/accounts")
public String handle(@ModelAttribute Account account, BindingResult errors) {
    // ...
}

In addition, any model attributes that have a reactive type wrapper are resolved to their actual values (and the model updated) just prior to view rendering.

https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-modelattrib-methods

  • Related