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

升级Spring Boot 3后Jersey Client 3中@JsonProperty失效问题

问题解决:Spring Boot 3 + Jersey Client 3 下 @JsonProperty 下划线属性映射失效

问题重现

升级到Spring Boot 3并使用Jersey Client 3后,DTO中带下划线命名的refresh_token、expires_in属性无法通过@JsonProperty正确映射,仅scope属性正常工作:

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class SomeResponseDTO {

  @JsonProperty("refresh_token")
  private String refreshToken;

  @JsonProperty("expires_in")
  private int expiresIn;

  @JsonProperty("scope")
  public String scope;
}

通过response.readEntity(SomeResponseDTO.class)转换响应时,refreshToken和expiresIn始终为默认值,scope能正确赋值,更换Jackson 2.15版本后问题仍存在。

解决方案

1. 给Jersey Client注册Jackson消息转换器

Jersey 3默认用MOXy作为JSON处理器,而非Jackson,这会导致Jackson的@JsonProperty注解不生效。需要手动注册JacksonFeature:

import org.glassfish.jersey.jackson.JacksonFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;

@Configuration
public class JerseyClientConfig {
    @Bean
    public Client jerseyClient() {
        return ClientBuilder.newBuilder()
                .register(JacksonFeature.class)
                .build();
    }
}

2. 检查Jackson全局命名策略配置

如果项目配置了全局Jackson命名策略,可能会覆盖@JsonProperty的局部配置。可以在application.yml中明确指定默认策略:

spring:
  jackson:
    property-naming-strategy: DEFAULT

3. 统一DTO字段访问修饰符并验证Getter/Setter

前两个字段为private,第三个为public,这种不一致可能导致Jersey的序列化处理器行为异常。建议统一将所有字段设为private,若仍有问题,可显式指定@JsonProperty的访问级别:

@JsonProperty(value = "refresh_token", access = JsonProperty.Access.READ_WRITE)
private String refreshToken;

@JsonProperty(value = "expires_in", access = JsonProperty.Access.READ_WRITE)
private int expiresIn;

4. 排除Jersey默认的MOXy依赖

如果项目不需要MOXy,可在依赖中排除它避免冲突:
Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jersey</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.moxy</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Gradle:

implementation('org.springframework.boot:spring-boot-starter-jersey') {
    exclude group: 'org.eclipse.persistence', module: 'org.eclipse.persistence.moxy'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:48:21