gpt4 book ai didi

java - Spring webflux 不使用 @ModelAttribute 从路径变量填充自定义对象

转载 作者:行者123 更新时间:2023-12-01 14:21:20 29 4
gpt4 key购买 nike

我正在尝试调整一个与 Spring MVC 配合良好但与 Spring WebFlux 有不同行为的应用程序

这是我使用 Spring Boot 5 - Spring MVC 的代码:

Controller :

@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 一起工作。

有没有人遇到过和我一样的问题?

谢谢,

朱利安

最佳答案

Spring WebFlux reference documentation about @ModelAttributethe same section in the reference documentation for Spring MVC 不同,未提及 URI 路径变量:

The Pet instance above is resolved as follows:

  • From the model if already added by using Model.
  • From the HTTP session by using @SessionAttributes.
  • From a URI path variable passed through a Converter (see the next example).
  • From the invocation of a default constructor.
  • From the invocation of a “primary constructor” with arguments that match to Servlet request parameters. Argument names are determined through JavaBeans @ConstructorProperties or through runtime-retained parameter names in the bytecode.

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

关于java - Spring webflux 不使用 @ModelAttribute 从路径变量填充自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53253955/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com