You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非Spring Boot环境Spring REST返回Employee类报No converter found问题求助

报错原因及解决思路

这个报错本质是Spring MVC没有找到能够将Employee自定义对象序列化为HTTP响应内容(通常是JSON格式)的消息转换器,你已经给Employee加了getter方法,问题出在手动集成Spring的配置缺失,可按以下步骤排查:

1. 检查JSON序列化依赖

Spring MVC默认使用Jackson完成Java对象到JSON的序列化,手动集成项目不会自动引入该依赖,需要自行添加:

  • Maven项目在pom.xml中添加以下依赖(注意版本和你使用的Spring版本兼容):
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>对应兼容版本号</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>对应兼容版本号</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>对应兼容版本号</version>
</dependency>
  • 非Maven项目需要手动导入上述三个Jar包到项目的lib目录。

2. 检查Spring MVC的消息转换器配置

手动集成Spring MVC需要显式开启注解驱动并注册Jackson消息转换器:

如果你用XML配置Spring MVC:

确保Spring的配置文件中添加了<mvc:annotation-driven/>标签,该标签会自动检测项目中存在的Jackson依赖并注册对应的JSON消息转换器。如果需要显式配置可以添加:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

如果你用Java类配置Spring MVC:

让配置类实现WebMvcConfigurer接口,重写消息转换器配置方法:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.codestrs")
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter());
    }
}

3. 检查代码修饰符问题

你当前的代码存在两处访问权限问题可能导致序列化/请求处理失败:

  • Employee类的无参构造方法是包访问权限,Jackson反射创建对象可能失败,建议修改为public Employee() {}
  • Controller中的one请求处理方法没有加public修饰符,Spring MVC无法识别该方法为请求处理入口,建议修改为public Employee one(@PathVariable Long id)

完成上述排查后重启项目即可解决该问题。


内容的提问来源于stack exchange,提问作者A_Name

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:36:04