【问题标题】:Why Spring Boot not using custom ObjectMapper bean?为什么 Spring Boot 不使用自定义 ObjectMapper bean?
【发布时间】:2021-07-27 08:08:59
【问题描述】:

我有自定义 ObjectMapper bean 注释为 @Primary。

@Configuration
public class BeanConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new Jdk8Module());
        objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
        return objectMapper;
    }

}

但是,当我尝试使用不同大小写的枚举来解析表单时,它给了我错误。

@RestController
@RequestMapping("/game")
public class GameController {

    private final GameService gameService;

    public GameController(GameService gameService) {
        this.gameService = gameService;
    }

    @PostMapping("/create")
    public ResponseEntity<?> createGame(
            @AuthenticationPrincipal String id,
            GameParametersForm gameParametersForm
    ) {
        Result<String> result = gameService.createWebGameSession(id, gameParametersForm);
        return result.toResponseEntity();
    }

}
public class GameParametersForm {

    private Mode mode;

    public GameParametersForm(
            Mode mode
    ) {
        this.mode = mode;
    }

    public Mode getMode() {
        return mode;
    }

}

这里是 build.gradle

plugins {
    id 'org.springframework.boot' version '2.4.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
    maven { url 'https://jitpack.io' }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.fasterxml.jackson.core:jackson-annotations:2.12.2'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.2'
    implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.12.2'
    implementation 'javax.validation:validation-api:2.0.1.Final'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-websocket'
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.security:spring-security-test'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

我试图声明 Jackson2ObjectMapperBuilder bean。它没有帮助。
知道可能会发生什么,或者我应该在哪里寻找问题?

【问题讨论】:

  • 请添加您的 json 有效负载
  • @VovaBilyachat 我该怎么做?它是来自网页的表格。问题是当我在正确的情况下发送相同的枚举时它不会给我一个错误。
  • 您不需要重新定义 bean,只需编辑 application.properties 以启用所需的功能。见github.com/spring-projects/spring-boot/blob/main/…
  • @andreoss spring.jackson.mapper.accept-case-insensitive-enums=true 属性也没有给出任何结果
  • 所以我检查了杰克逊的问题mb。因为在我只在application.properties 中添加了功能之后,没有添加 ObjectMapper bean。并且 loggin 启用了 autowired ObjectMapper 的映射器功能,该功能已启用,但仍然存在同样的问题。

标签: java spring spring-boot


【解决方案1】:

检查您是否让 spring boot 自动配置您的应用程序。在您的 Spring Boot 应用程序配置中,少即是多。如果你添加了@EnableWebMvc,你会阻止 spring boot 自动配置你的序列化和反序列化。

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-spring-mvc-auto-configuration

【讨论】:

  • 我在任何配置中都没有@EnableWebMvc 注释。
【解决方案2】:
  1. 创建一个Jackson2ObjectMapperBuilderCustomizer bean,例如。 hantsy/spring-r2dbc-sample DemoApplication.java#L152
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
            builder.featuresToDisable(
                    SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                    SerializationFeature.FAIL_ON_EMPTY_BEANS,
                    DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,
                    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            builder.featuresToEnable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        };
    }
    
  2. 或者在spring boot应用属性中自定义。例如。 hantsy/spring-webmvc-jwt-sample application.yml#L4
     spring:
       jackson:
         mapper:
           DEFAULT_VIEW_INCLUSION: true
         serialization:
           indent_output: true
           WRITE_DATES_AS_TIMESTAMPS: false
         deserialization:
           FAIL_ON_IGNORED_PROPERTIES: false
           FAIL_ON_UNKNOWN_PROPERTIES: false
           ACCEPT_SINGLE_VALUE_AS_ARRAY: true
         default-property-inclusion: non_empty
    

【讨论】:

  • @north32 请删除您的 Jackson 部门,网络启动器将包含它们。 Jackson 2.12 API 中有一些重大变化。我认为 Spring Boot 2.4.x 将与 2.11.x 保持一致
  • 不工作。我找到了使用 json data + @RequestBody 的解决方案
  • @north32 你的问题和Jackson一点关系都没有。
猜你喜欢
  • 2018-08-14
  • 1970-01-01
  • 2016-09-10
  • 2020-08-15
  • 2019-07-30
  • 2019-04-21
  • 1970-01-01
  • 2015-06-25
  • 2019-03-02
相关资源
最近更新 更多