一.问题描述
今天在使用腾讯短信sdk进行Maven项目依赖过程中
添加以下依赖包:
<!-- 腾讯云-短信功能 -->
<dependency>
<groupId>com.github.qcloudsms</groupId>
<artifactId>qcloudsms</artifactId>
<version>1.0.6</version>
</dependency>
调用短信发送方法(模板发送)时项目报错,如下:
rg.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/apache/http/client/config/RequestConfig
at org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1305)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:979)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
......
Caused by: java.lang.NoClassDefFoundError: org/apache/http/client/config/RequestConfig
at com.github.qcloudsms.httpclient.DefaultHTTPClient.fetch(DefaultHTTPClient.java:29)
at com.github.qcloudsms.SmsSingleSender.sendWithParam(SmsSingleSender.java:127)
at com.github.qcloudsms.SmsSingleSender.sendWithParam(SmsSingleSender.java:143)
at com.dz.sms.SmsUtil.sendTemplateSingleSms(SmsUtil.java:65)
二.原因分析
1.经过网上查找,大多数都说是缺少 httpclient 包
但本项目中已经添加了 httpclient 包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.5</version>
</dependency>
2.查看 Maven 依赖关系
发现 腾讯 qcloudsms 包依赖使用的 httpclient 4.5.3 ,原因终于找到了
jar包直接有冲突!
三.解决方法
方法1.修改原项目中的 httpclient 包版本号和 qcloudsms 中的版本号一致(4.5.3)。
方法2.使用 maven-shade 插件,过滤包冲突
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>org.apache.httpcomponents</pattern>
<shadedPattern>org.shaded.org.apache.httpcomponents</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
主要是配置使用 relocations 重命名冲突包
<configuration>
<relocations>
<relocation>
<pattern>org.apache.httpcomponents</pattern>
<shadedPattern>org.shaded.org.apache.httpcomponents</shadedPattern>
</relocation>
</relocations>
</configuration>