我目前正在处理一个SpringWebflux微服务,并尝试实现一个@PatchMapping,它将JsonPatch对象作为@RequestBody使用,如下所示:
@PatchMapping("/{id}", consumes = ["application/json-patch+json"])
fun updateFriend( @PathVariable("id") id: Long,
@Valid @RequestBody jsonPatch: JsonPatch): Mono<UserFriends> {
// apply JsonPatch code here...
}
我用一个Postman请求测试了端点,如下所示:
PATCH <microservice-uri>/friends/1
Content-Type = application/json-patch+json
RequestBody =
[
{
"op": "replace",
"path": "friends/11/since",
"value": "<sample value>"
}
]
这是我遇到的例外:
org.springframework.core.codec.CodecException: Type definition error: [simple type, class javax.json.JsonPatch]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `javax.json.JsonPatch` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]
at org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:211) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ⇢ HTTP PATCH "/friends/1" [ExceptionHandlingWebHandler]
<Additional stacktraces here ...>
我很清楚,我需要告诉我的微服务如何将RequestBody转换为JsonPatch。但是在失败了3天之后,我决定寻求一些帮助。
经过多次不成功的尝试,我找到了WebFluxConfigurer
,并尝试覆盖configureArgumentResolvers
。我在为JsonPatch编写HandlerMethodArgumentResolver
时卡住了。
class JsonPatchResolver : HandlerMethodArgumentResolver {
override fun supportsParameter(parameter: MethodParameter): Boolean {
// Don't know what to implement here
}
override fun resolveArgument(parameter: MethodParameter, bindingContext: BindingContext, exchange: ServerWebExchange): Mono<Any> {
// Don't know how to create a JsonPatch from the given arguments
}
}
有人能给我指个方向吗?或者告诉我哪里做错了?
非常感谢你提前!
编辑这是我的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>friend-info-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>friend-info-service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<kotlin.version>1.3.72</kotlin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-patch</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr353</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
EDIT 2以下内容不起作用:
class JsonPatchArgumentResolver : HandlerMethodArgumentResolver {
override fun supportsParameter(parameter: MethodParameter): Boolean {
// this doesn't event get called when debugging, so I suspect the handler isn't registered correctly
return parameter.parameterType == JsonPatch::class
}
override fun resolveArgument(parameter: MethodParameter, bindingContext: BindingContext, exchange: ServerWebExchange): Mono<Any> {
return exchange.request.body.toMono().map {
jacksonObjectMapper().readValue(it.asInputStream(), JsonPatch::class.java)
}
}
}
在我的应用程序类中,我注册了它(可能是错误的,我不知道):
@SpringBootApplication
@EnableReactiveMongoRepositories
@EnableWebFlux
@Configuration
class FriendInfoServiceApplication : WebFluxConfigurer {
override fun configureArgumentResolvers(configurer: ArgumentResolverConfigurer) {
configurer.addCustomResolver(JsonPatchArgumentResolver())
}
}
fun main(args: Array<String>) {
runApplication<FriendInfoServiceApplication>(*args)
}
EDIT 3在调试时,我确实发现configureArgumentResolvers
被调用了,所以也许我在supportsParameter
上做错了什么?
EDIT 4我试着从THIS博客文章中复制代码。Kotlin的等效代码应该是:
@Component
class JsonPatchHttpMessageConverter : AbstractHttpMessageConverter<JsonPatch>() {
@Throws(HttpMessageNotReadableException::class)
protected override fun readInternal(clazz: Class<out JsonPatch>, inputMessage: HttpInputMessage): JsonPatch {
try {
Json.createReader(inputMessage.body).use { reader -> return Json.createPatch(reader.readArray()) }
} catch (e: Exception) {
throw HttpMessageNotReadableException(e.message!!, inputMessage)
}
}
@Throws(HttpMessageNotWritableException::class)
protected override fun writeInternal(jsonPatch: JsonPatch, outputMessage: HttpOutputMessage) {
throw NotImplementedError("The write Json patch is not implemented")
}
protected override fun supports(clazz: Class<*>): Boolean {
return JsonPatch::class.java.isAssignableFrom(clazz)
}
}
并将objectMapper添加到Application类,如下所示:
@SpringBootApplication
@EnableReactiveMongoRepositories
@EnableWebFlux
@Configuration
class FriendInfoServiceApplication {
@Bean
fun objectMapper(): ObjectMapper {
val objectMapper = ObjectMapper()
objectMapper.registerModule(JSR353Module())
return objectMapper
}
}
不幸的是,结果是在尝试调用PATCH端点时出现相同的异常。
2条答案
按热度按时间qxgroojn1#
我是你提到的博客文章的作者。我不是Webflux方面的Maven,但在这种情况下,你必须重新实现jacksonConverter到webFlux表单。
于是它变成了这样:
请注意,它没有完全实现,您必须进行错误处理并实现
read(elementType: ResolvableType, message: ReactiveHttpInputMessage, hints: Map<String, Any>): Flux<JsonPatch>
。现在你必须注册这个定制的解码器。在spring webFlux中,你可以通过创建一个WebFluxConfigurer bean来完成:
最后是路由器和处理程序:
最后,您可以使用curl调用此端点,例如:
33qvvth12#
非常感谢@Hugo Alves提供的这段代码,但是这里有一个内存泄漏,你应该释放缓冲区: