Spring启动MVC不使用指定的自定义StringHttpMessageConverter

时间:2015-09-17 09:06:57

标签: java spring-mvc spring-boot

在负责app app的类中有以下代码:

@Bean
public HttpMessageConverter<String> createStringHttpMessageConverter() {

    StringHttpMessageConverter converter = new StringHttpMessageConverter
            (Charset.forName("UTF-8"));

    return converter;
}

我在调试器中检查过它实际执行了,并尝试使用StringHttpMessageConverter作为返回类型。

然而,当我调试WebMvcConfig.extendMessageConverters()时,我看到使用带有默认字符集的StringHttpMessageConverter而不是使用带有UTF-8字符集的转换器。

为什么Spring Boot不使用指定的StringHttpMessageConverter

我知道解决方法可能是根据WebMvcConfig.extendMessageConverters()中的需要更改转换器列表,但我想以正确的方式执行

2 个答案:

答案 0 :(得分:1)

使用Spring Boot try to register array of HttpMessageConverters

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;

@Configuration
public class MyConfiguration {

    @Bean
    public HttpMessageConverters customConverters() {
        HttpMessageConverter<?> additional = ...
        HttpMessageConverter<?> another = ...
        return new HttpMessageConverters(additional, another);
    }

}

或者如果您没有使用Spring Boot的自动配置,您可以使用标准的Spring WebMvcConfigurer for registering converters

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                .indentOutput(true)
                .dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
                .modulesToInstall(new ParameterNamesModule());
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.xml().build()));
    }

}

答案 1 :(得分:0)

您需要2个步骤来支持utf-8 StringHttpMessageConverter; 首先添加StringHttpMessageConverter;其次在yield中指定charset,代码在下面;

@RestController

@RequestMapping(value =“/ plain”) public class PlainController {

@RequestMapping(value = "/test", method = RequestMethod.GET,
        produces = {"text/plain;charset=UTF-8"})
public Response<String> test() {

    return new Response<String>("success");
}

}

@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    fastConverter.setFastJsonConfig(fastJsonConfig);
    HttpMessageConverter<?> converter = fastConverter;

    StringHttpMessageConverter stringHttpMessageConverter =
            new StringHttpMessageConverter(Charset.forName("UTF-8"));
    return new HttpMessageConverters(converter, stringHttpMessageConverter);
}