Spring Webflux不会使用@ModelAttribute从路径变量中填充自定义对象

时间:2018-11-11 22:38:12

标签: java spring spring-mvc spring-boot spring-webflux

我正在尝试改编一个与Spring MVC兼容但与Spring WebFlux具有不同行为的应用程序

这是Spring Boot 5-Spring MVC的代码:

控制器:

@RestController
public class MyRestController {

    @GetMapping("/test/{id}/{label}")
    public ResponseEntity<Payload> test(@ModelAttribute Payload payload) {
        return new ResponseEntity<>(payload,HttpStatus.OK);
    }
}

有效载荷对象:

public class Payload {

    @NotNull
    private int id;

    private String label;

    public Payload() {}

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

我的pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

我还没有编写任何自定义转换器,Spring自动填充了我的有效负载对象,一切都很好。

当我打电话时:

http://localhost:8080/test/25/helloWorld

响应为

{"id":25,"label":"helloWorld"}

然后,我只更改pom.xml,从web切换到webflux:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
</dependencies>

并且不再填充我的有效载荷对象。

当我打电话时:

http://localhost:8080/test/25/helloWorld

响应为

{"id":0,"label":null}

我知道我可以编写一个转换器并在@ControllerAdvice中注册它,但是我无法想象没有一种自动化的解决方案可以使它再次运行,因为它一直与Spring Web一起使用。

是否有人已经遇到与我相同的问题?

谢谢

朱利安

1 个答案:

答案 0 :(得分:1)

Spring WebFlux reference documentation about @ModelAttribute不同,the same section in the reference documentation for Spring MVC没有提到URI路径变量:

  

上面的Pet实例解析如下:

     
      
  • 从模型中获取(如果已经通过使用Model添加)。
  •   
  • 使用@SessionAttributes在HTTP会话中。
  •   
  • 来自通过Converter的URI路径变量(请参阅下一个   例如)。
  •   
  • 通过默认构造函数的调用。
  •   
  • 通过调用具有以下参数的“主要构造函数”   与Servlet请求参数匹配。确定参数名称   通过JavaBeans @ConstructorProperties或通过运行时保留   字节码中的参数名称。
  •   

这是预期的行为,选择之后可能有充分的理由或限制。 Feel free to open an enhancement request in Spring Framework for that