복붙노트

[SPRING] 봄과 잭슨, @ResponseBody를 통해 FAIL_ON_EMPTY_BEANS를 사용 중지하는 방법

SPRING

봄과 잭슨, @ResponseBody를 통해 FAIL_ON_EMPTY_BEANS를 사용 중지하는 방법

@ResponseBody로 주석 된 모든 컨트롤러에 대해 봄 FAIL_ON_EMPTY_BEANS를 비활성화 할 수있는 봄에 전역 구성이 있습니까?

해결법

  1. ==============================

    1.configureMessageConverters를 구성 할 때 객체 매퍼를 구성 할 수 있습니다.

    configureMessageConverters를 구성 할 때 객체 매퍼를 구성 할 수 있습니다.

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        MappingJackson2HttpMessageConverter converter = 
            new MappingJackson2HttpMessageConverter(mapper);
        return converter;
    }
    

    응용 프로그램에서 정확하게 수행하는 방법을 알고 싶다면 구성 파일 (xml 또는 java configs)을 사용하여 질문을 업데이트하십시오.

    다음은 메시지 변환기를 사용자 정의하는 좋은 방법입니다.

    편집 : Java 구성 대신 XML을 사용하는 경우 사용자 지정 구성으로 ObjectMapper를 확장하는 사용자 지정 MyJsonMapper 클래스를 만든 다음 다음과 같이 사용할 수 있습니다

    public class MyJsonMapper extends ObjectMapper {    
            public MyJsonMapper() {
                this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            }
    }
    

    XML에서 :

    <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper" ref="jacksonObjectMapper" />
                </bean>
            </mvc:message-converters>
    </mvc:annotation-driven>
    
    
    <bean id="jacksonObjectMapper" class="com.mycompany.example.MyJsonMapper" >
    
  2. ==============================

    2.Spring Boot를 사용하는 경우 application.properties 파일에서 다음 등록 정보를 설정할 수 있습니다.

    Spring Boot를 사용하는 경우 application.properties 파일에서 다음 등록 정보를 설정할 수 있습니다.

    spring.jackson.serialization.FAIL_ON_EMPTY_BEANS = false

    그의 귀중한 의견에 대해 @DKroot에게 감사드립니다. 그러나 나는 이것이 다른 사람들을위한 자체 답변이어야한다고 생각한다.

  3. from https://stackoverflow.com/questions/28862483/spring-and-jackson-how-to-disable-fail-on-empty-beans-through-responsebody by cc-by-sa and MIT license