Spring Boot 2无法识别MappingJackson2HttpMessageConverter配置

时间:2018-08-19 01:32:41

标签: java spring hibernate spring-boot jackson-databind

我已经使用Spring一段时间了,在我的Spring Boot 1.5x的项目中,总是使用下一个配置(在楼下)处理LazyInitializationException,但是现在我正在使用Spring Boot 2创建一个新项目,并且相同的配置是不再比WebMvcConfigurer更好地被识别,现在替换为已弃用的WebMvcConfigurerAdapter。

我的配置:

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
    @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            converters.add(jacksonMessageConverter());
            WebMvcConfigurer.super.configureMessageConverters(converters);
        }
        public MappingJackson2HttpMessageConverter jacksonMessageConverter() {
            MappingJackson2HttpMessageConverter messageConverter =
                    new MappingJackson2HttpMessageConverter();

            List<MediaType> supportedMediaTypes=new ArrayList<>();
            supportedMediaTypes.add(MediaType.APPLICATION_JSON);
            supportedMediaTypes.add(MediaType.TEXT_PLAIN);
            messageConverter.setSupportedMediaTypes(supportedMediaTypes);

            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new Hibernate5Module());
            messageConverter.setObjectMapper(mapper);

            messageConverter.setPrettyPrint(true);

            return messageConverter;
        }
}

但是在那之后我仍然出现错误:

[WARN ] 2018-08-18 20:07:08.694 DESKTOP-ABFFHEJ --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy [com.ideatik.domain.TipoUsuario#3] - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [com.ideatik.domain.TipoUsuario#3] - no Session (through reference chain: com.ideatik.domain.Usuario["tipoUsuario"]->com.ideatik.domain.TipoUsuario_$$_jvst9b7_2["nombre"])
[WARN ] 2018-08-18 20:07:08.695 DESKTOP-ABFFHEJ --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy [com.ideatik.domain.TipoUsuario#3] - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [com.ideatik.domain.TipoUsuario#3] - no Session (through reference chain: com.ideatik.domain.Usuario["tipoUsuario"]->com.ideatik.domain.TipoUsuario_$$_jvst9b7_2["nombre"])

感谢进阶!

1 个答案:

答案 0 :(得分:0)

尝试在方法中添加 @Bean

@Bean
public MappingJackson2HttpMessageConverter jacksonMessageConverter() {
   .....
}