属性
你可以为请求添加属性。如果你想通过过滤器链传递信息,并影响特定请求的过滤器行为,这将非常方便。例如:
- Java
- Kotlin
WebClient client = WebClient.builder()
.filter((request, next) -> {
Optional<Object> usr = request.attribute("myAttribute");
// ...
})
.build();
client.get().uri("https://example.org/")
.attribute("myAttribute", "...")
.retrieve()
.bodyToMono(Void.class);
}
val client = WebClient.builder()
.filter { request, _ ->
val usr = request.attributes()["myAttribute"];
// ...
}
.build()
client.get().uri("https://example.org/")
.attribute("myAttribute", "...")
.retrieve()
.awaitBody<Unit>()
请注意,你可以在WebClient.Builder级别全局配置一个defaultRequest回调函数,该函数允许你将属性插入到所有请求中。例如,在Spring MVC应用程序中,可以利用这一功能根据ThreadLocal数据来填充请求属性。