Skip to content

Spring webflux @ModelAttribute annotated methods not working with kotlin suspend methods #30894

Closed

Description

@BarracudaX

I am using spring webflux with spring boot 3.1.0 and 1.1.0 io.spring.dependency-management gradle plugin(spring webflux 6.0.9).
According to documentation, spring should call methods annotated with @ModelAttribute before any @RequestMapping, and it should support reactive types for web flux. This works fine for Mono and Flux return types, but it doesn't work with kotlin suspend functions.


@Controller
class ViewController {

    @GetMapping("/")
    suspend fun homePage() : String {
        return "index"
    }
    @ModelAttribute(name = "roles")
    suspend fun roleAttributeInitializer(model: Model) : List<String>{
        return ReactiveSecurityContextHolder.getContext().map { sec -> sec.authentication?.authorities?.map { it.authority } ?: emptyList() }.awaitSingle()
    }

    @ModelAttribute
    suspend fun roleAttributeInitializer2(model: Model){
        model.addAttribute("roles",ReactiveSecurityContextHolder.getContext().map { sec -> sec.authentication?.authorities?.map { it.authority } ?: emptyList() })
    }

}

In the example above, methods annotated with @ModelAttribute are invoked after the @GetMapping annotated method when I debug with breakpoints.
Also, the first suspend method,even though invoked after @GetMapping, still populates the model correctly because it doesn't cause NullPointerException when rendering the view. But the second suspend method,which is also invoked after the @GetMapping, doesn't populate the model and I am getting NullPointerException when rendering the view because roles is null.

Activity

  1. self-assigned this
    on Aug 18, 2023
  2. added
    in: webIssues in web modules (web, webmvc, webflux, websocket)
    and removed on Sep 13, 2023
  3. added this to the 6.0.12 milestone on Sep 13, 2023
  4. added a commit that references this issue on Sep 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)theme: kotlinAn issue related to Kotlin supporttype: bugA general bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions