보통은 org.springframework.web.HttpMediaTypeNotSupportedException 예외는


Rest api에서 허용할 수 있는 MediaType이 아니면 에러가 난다.

@RequestMapping(path="/api/1", 
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, 
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)


ResultActions result =
mockMvc.perform(post("/api/1/city")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(requestJson))
.andDo(print());




그러나, 특별한 경우로 

SpringBoot의 UI 모델 또는 DTO에  lombok, Jackson의 JsonCreator가 잘못 결합될 때. 이상한 에러가 난다.

그래서 몇시간동안 삽질, 주화 입마에 빠질 수 있다.    

org.springframework.web.HttpMediaTypeNotSupportedException






문제가 되는 코드는 다음과 같다.


@RestController

@RequestMapping("/api/test")

public class CityController {


    @PostMapping

    public Product post(@RequestBody City city) {

.....

    }


}




@Data

public class City {

@NonNull

private Long id;


@NonNull

private String name;


@NonNull

private Integer population;


@JsonCreator

public City(Long id, String name, Integer population) {

this.id = id;

this.name = name;

this.population =  population;

}

}


또는 아래와 같이 AllArgsConstructor에 JsonCreator를 사용하면 안된다.


@Data

@Builder

@AllArgsConstructor(onConstructor = @__(@JsonCreator))

public class City {


@NonNull


private Long id;




@NonNull


private String name;




@NonNull


private Integer population;

}


HttpMediaTypeNotSupportedException가 발생한다.



따라서  아래와 같이 모델을 변경하니 잘 동작한다.

@Data

@AllArgsConstructor

@NoArgsConstructor

public class City {

@NonNull

private Long id;


@NonNull

private String name;


@NonNull

private Integer population;

}




이미 보고는 되어 있는데..  해결 방안은  딱히 없으니. 알아서 잘 피해야 할 것 같다. 



https://github.com/FasterXML/jackson-databind/issues/1239

https://github.com/spring-projects/spring-boot/issues/12568


Posted by '김용환'
,