实例化RestTemplate时出现异常

时间:2018-03-28 10:36:51

标签: spring spring-mvc jackson jackson-dataformat-xml

使用Rest Template在Maven项目中使用Web服务并将项目打包到jar以作为依赖项添加到我的其他Web应用程序 但是在实例化RestTemplate时将Exception抛出到控制台,即使我把代码捕获到异常,它直接将下面的Exception抛给控制台。任何人都可以知道原因吗?

try{
  RestTemplate restTemplate = new RestTemplate(); //getting the Exception here
}
catch(Exception e){
  e.printStackTrace(); // but its not coming here 
}

我在pom.xml文件中添加的依赖项:

<!-- Spring dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.9.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <!-- JSON-Binding -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>1.1.0.1</version>
            <scope>provided</scope>
        </dependency>

服务器端的异常是:

Root cause of ServletException.
java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.SerializationConfig.withDefaultPrettyPrinter(Lcom/fasterxml/jackson/core/PrettyPrinter;)Lcom/fasterxml/jackson/databind/SerializationConfig;
    at com.fasterxml.jackson.dataformat.xml.XmlMapper.<init>(XmlMapper.java:86)
    at com.fasterxml.jackson.dataformat.xml.XmlMapper.<init>(XmlMapper.java:67)
    at com.fasterxml.jackson.dataformat.xml.XmlMapper.<init>(XmlMapper.java:63)
    at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder$XmlObjectMapperInitializer.create(Jackson2ObjectMapperBuilder.java:807)
    at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:585)
    Truncated. see log file for complete stacktrace
> 

2 个答案:

答案 0 :(得分:0)

您可能希望在类路径中包含正确版本的jackson-databind jar文件。 servlet容器尚未开始访问您的代码库。

答案 1 :(得分:0)

使用相同的版本在pom.xml中提供以下所有依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson.version}</version>
</dependency>

这应该有所帮助。