【发布时间】:2018-07-24 16:08:11
【问题描述】:
在使用 Spring WebFlux 时,我无法将我设置的属性从 WebTestClient 绑定到 RestController。
我尝试了我能想到的两种方法。
首先使用@RequestAttribute注解,我得到了:
无法处理请求 [GET /attributes/annotation]:响应状态 400,原因为“缺少字符串类型的请求属性‘属性’”
然后我尝试使用 ServerWebExchange 并且是 null。
这是我的控制器:
@RestController
@RequestMapping("/attributes")
public class MyController {
@GetMapping("/annotation")
public Mono<String> getUsingAnnotation(@RequestAttribute("attribute") String attribute) {
return Mono.just(attribute);
}
@GetMapping("/exchange")
public Mono<String> getUsingExchange(ServerWebExchange exchange) {
return Mono.just(exchange.getRequiredAttribute("attribute"));
}
}
这是我失败的测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyControllerTest {
@Autowired
ApplicationContext context;
WebTestClient webClient;
@Before
public void setup() {
webClient = WebTestClient.bindToApplicationContext(context)
.configureClient()
.build();
}
@Test
public void testGetAttributeUsingAnnotation() {
webClient.get()
.uri("/attributes/annotation")
.attribute("attribute", "value")
.exchange()
.expectStatus()
.isOk();
}
@Test
public void testGetAttributeUsingExchange() {
webClient.get()
.uri("/attributes/exchange")
.attribute("attribute", "value")
.exchange()
.expectStatus()
.isOk();
}
}
在我的真实应用程序中,我有一个 SecurityContextRepository,它从(解码的)标头值设置一些属性,我想获取这些属性。
【问题讨论】:
标签: java spring-webflux