仅在Eclipse运行时Spring Boot Controller POST请求报HTTP 415错误
问题现象
你的Spring Boot后端在Docker、java -jar或IntelliJ中运行完全正常,但在Windows Server 2016的Eclipse中启动后,发送带JSON体的POST请求会触发HTTP 415 Unsupported Media Type错误,核心日志提示Jackson反序列化失败:
2020-03-09 15:09:52.515 WARN 218960 --- [nio-8080-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class xxx.xxx.xxx.xxx.xxx.xxx.xxx]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid type definition for type
xxx.xxx.xxx.xxx.xxx.xxx.xxx: Argument #0 has no property name, is not Injectable: can not use as Creator [constructor for xxx.xxx.xxx.xxx.xxx.xxx.xxx, annotations: {interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}]
无论前端是否显式设置Content-Type: application/json,错误都会出现,且你已确认Eclipse编码、JDK版本、依赖包与IntelliJ完全一致。
核心原因
问题出在ConnectionConfiguration类的@JsonCreator注解使用方式,以及Eclipse编译环境对Java参数名称的处理差异:
- 当你仅给构造函数添加
@JsonCreator但未给构造参数指定@JsonProperty时,Jackson需要依赖参数名称来匹配JSON字段,但Eclipse默认编译时不会保留参数名称信息(除非开启特定编译选项),而IntelliJ和Gradle默认会保留这部分信息。 - 虽然你用的是Java 11,但Eclipse的ECJ编译器默认没有启用
-parameters编译参数,导致Jackson无法识别构造函数参数的名称,进而无法完成JSON反序列化,最终抛出415错误。
解决方案
你有三种方式可以解决这个问题,完美适配Eclipse开发环境:
1. 给构造函数参数添加@JsonProperty注解(推荐)
修改ConnectionConfiguration类的构造函数,明确指定参数对应的JSON字段名,这样Jackson无需依赖参数名称就能完成匹配,不受编译环境影响:
package xxx.xxx.xxx.xxx.xxx.xxx; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class ConnectionConfiguration { private String someProperty; @JsonCreator public ConnectionConfiguration(@JsonProperty("someProperty") String someProperty) { this.someProperty= someProperty; } public String getSomeProperty() { return someProperty; } }
2. 在Eclipse中手动启用-parameters编译参数
让Eclipse编译时保留参数名称信息,操作步骤如下:
- 右键项目 → Properties → Java Compiler
- 勾选Store information about method parameters (usable via reflection)(对应
-parameters编译参数) - 点击Apply and Close,然后执行Clean并重新编译项目
3. 通过Gradle统一配置编译参数
如果项目基于Gradle构建,在backend模块的build.gradle中添加以下配置,确保无论用什么IDE编译,都强制保留参数名称:
tasks.withType(JavaCompile) { options.compilerArgs << '-parameters' }
这样Eclipse导入Gradle项目时会自动继承该配置,无需手动设置。
验证方式
修改完成后,在Eclipse中重启后端服务,重新发送POST请求,应该可以正常接收JSON体并完成反序列化,不再返回415错误。
内容的提问来源于stack exchange,提问作者mfbieber

