Webclient maven依赖错误

Posted

技术标签:

【中文标题】Webclient maven依赖错误【英文标题】:Webclient maven Dependency errors 【发布时间】:2020-06-29 00:00:15 【问题描述】:

我在尝试使用“create”创建 WebClient 实例的行上收到 NoClassDefFoundError。试过 builder() 但还是一样。

请告诉我我添加的依赖项有什么问题以及如何解决此问题。

             webClient = WebClient.create(url)
                                .post()
                                .uri(uri)
                                .contentType(MediaType.APPLICATION_JSON)
                                .body(BodyInserters.fromMultipartData(map))
                                .retrieve()
                                .bodyToMono(Object.class)
                                .block()
                                .toString()

我添加的依赖是

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
        </dependency>

堆栈跟踪:

Exception in Async java.lang.NoClassDefFoundError: reactor/netty/http/client/HttpClient

java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: reactor/netty/http/client/HttpClient
        
        at org.springframework.http.client.reactive.ReactorClientHttpConnector.<clinit>(ReactorClientHttpConnector.java:44)
        
        at org.springframework.web.reactive.function.client.DefaultWebClientBuilder.initExchangeFunction(DefaultWebClientBuilder.java:226)
        
        at org.springframework.web.reactive.function.client.DefaultWebClientBuilder.build(DefaultWebClientBuilder.java:207)
        
        at org.springframework.web.reactive.function.client.WebClient.create(WebClient.java:144)

Caused by: java.lang.NoClassDefFoundError: reactor/netty/http/client/HttpClient
        
        ... 16 common frames omitted

Caused by: java.lang.ClassNotFoundException: reactor.netty.http.client.HttpClient
        
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:92)
        
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        
        ... 16 common frames omitted

【问题讨论】:

【参考方案1】:

您需要在类路径中包含 reactor-netty。默认情况下,这是 WebClient 使用的 HTTP 客户端。

pom.xml

<dependency>
    <groupId>io.projectreactor.netty</groupId>
    <artifactId>reactor-netty</artifactId>
</dependency>

更多信息:https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-client

【讨论】:

以上是关于Webclient maven依赖错误的主要内容,如果未能解决你的问题,请参考以下文章

maven依赖范围

IntelliJ IDEA 定义的 maven pom 中的错误

转Maven实战---传递依赖

如何解决 Maven 中的循环依赖?

关于maven的规则插件:Maven Enforcer plugin

Maven -- Maven简介 & Maven下载与安装 & Maven目录结构 & Maven环境变量配置