【问题标题】:Spring-boot gets an error when creating custom RestTemplate创建自定义 RestTemplate 时 Spring-boot 出错
【发布时间】:2016-12-11 06:27:50
【问题描述】:

我有一个sendGetREST 方法来发送一些URL endpoint 并得到响应:

@Component
public class HttpURLCommand {
    private static Logger logger = Logger.getLogger(HttpURLCommand.class);

public String sendGetREST(String soapUrl, Object[] parameters) throws IOException{
        final String SOAP_URL = MessageFormat.format(soapUrl, parameters);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(SOAP_URL, String.class);

    logger.info("status code is: "+response.getStatusCode());
    if(response.getStatusCode().equals(HttpStatus.OK)){
        logger.info("send success");
        return response.getBody();
    }
    else {
        logger.info("send failed");
        return null;
    }

  }
}

效果很好。但是,为了使超时时间可定制,我从这个tutorial 得到了这个HTTPConfiguration

@Configuration
public class HTTPConfiguration {

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(clientHttpRequestFactory());
}

private ClientHttpRequestFactory clientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(60000);
    factory.setConnectTimeout(60000);
    return factory;
   }
}

所以这个类会像这样调用restTemplate:

@Component
 public class HttpURLCommand {
    private static Logger logger = Logger.getLogger(HttpURLCommand.class);
    @Autowired
    RestTemplate restTemplate;

public String sendGetREST(String soapUrl, Object[] parameters) throws IOException{
        final String SOAP_URL = MessageFormat.format(soapUrl, parameters);
        ResponseEntity<String> response = restTemplate.getForEntity(SOAP_URL, String.class);

    logger.info("status code is: "+response.getStatusCode());
    if(response.getStatusCode().equals(HttpStatus.OK)){
        logger.info("send success");
        return response.getBody();
    }
    else {
        logger.info("send failed");
        return null;
    }

  }
}

但不幸的是,在构建spring-boot 应用程序时返回以下错误:

Caused by: java.lang.NoClassDefFoundError: org/apache/http/protocol/HttpContext
at com.xl.MbbI.config.HTTPConfiguration.clientHttpRequestFactory(HTTPConfiguration.java:25) ~[classes/:na]
at com.xl.MbbI.config.HTTPConfiguration.restTemplate(HTTPConfiguration.java:21) ~[classes/:na]
at com.xl.MbbI.config.HTTPConfiguration$$EnhancerBySpringCGLIB$$191f99f.CGLIB$restTemplate$0(<generated>) ~[na:na]
at com.xl.MbbI.config.HTTPConfiguration$$EnhancerBySpringCGLIB$$191f99f$$FastClassBySpringCGLIB$$8330ce57.invoke(<generated>) ~[na:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.0.RC2.jar:4.3.0.RC2]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356) ~[spring-context-4.3.0.RC2.jar:4.3.0.RC2]
at com.xl.MbbI.config.HTTPConfiguration$$EnhancerBySpringCGLIB$$191f99f.restTemplate(<generated>) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_60]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.7.0_60]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.7.0_60]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.7.0_60]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.0.RC2.jar:4.3.0.RC2]
... 24 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.apache.http.protocol.HttpContext
at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.7.0_60]
at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.7.0_60]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.7.0_60]
at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.7.0_60]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.7.0_60]
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.7.0_60]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.7.0_60]
... 36 common frames omitted

仅供参考,错误远不止上面显示的。

第一行是这样的:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplate' defined in class path resource .....

【问题讨论】:

    标签: java spring spring-mvc spring-boot javabeans


    【解决方案1】:
    Caused by: java.lang.NoClassDefFoundError: org/apache/http/protocol/HttpContext
    

    错误说明你的类路径有问题,可能是因为你的类路径中没有类或.apache.http.protocol.HttpContext。 Spring RestTemplate 经常使用这个类。通常我们可以在 Apache httpclient 库中找到这个类。您应该再次检查您的依赖项。如果找不到,可以考虑添加下面的依赖(如果你使用Maven的话)

     <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>
    

    【讨论】:

    • 成功了!我不明白为什么它首先运行良好(没有自定义超时)?
    • 嗯...... .有人可以给我解释一下吗?
    • 默认情况下,RestTemplate 依赖标准 JDK 工具来建立 HTTP 连接。所以,第一名的效果很好。但是,在第二个中,您确实“告诉”了 RestTemplate 使用 ApacheHttpComponent 与 Web 服务进行通信。因此,由于找不到某些类,它引发了异常。这是您在第二个中的声明:@Bean public RestTemplate restTemplate() { return new RestTemplate(clientHttpRequestFactory()); }。首先,您使用默认的 httpcl
    • 这里是来自 Spring 网站的参考,它还提到了默认的 http 客户端。 docs.spring.io/spring/docs/current/javadoc-api/org/…
    • 在寻找解决方案一小时后,这是唯一有效的方法。谢谢!
    猜你喜欢
    • 2018-05-28
    • 2017-02-03
    • 2015-07-23
    • 2014-11-13
    • 1970-01-01
    • 2017-10-03
    • 2014-04-16
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多