为某些包Spring MVC

时间:2015-08-10 17:03:08

标签: java spring spring-mvc jackson

有没有办法使用spring为我的项目中的某些包设置HttpMessageConverter?

@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = MyConfig.class)
public class MyConfig
    extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJacksonHttpMessageConverter) {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
                objectMapper.setSerializationInclusion(Inclusion.NON_NULL);
                ((MappingJacksonHttpMessageConverter) converter).setObjectMapper(objectMapper);
            }
        }
    }

使用此PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES,更改项目中的所有响应,我希望这仅适用于某些dto。

1 个答案:

答案 0 :(得分:2)

这里是hzpz提出的解决方案的一个例子:

自定义转换器:

dependency hell

<强>配置

public class CustomConverter extends MappingJackson2HttpMessageConverter {

    private String basePackage;

    public CustomConverter(String basePackage) {
        this.basePackage = basePackage;
    }

    @Override
    public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
        if (contextClass.getName().startsWith(basePackage)) {
            return super.canRead(type, contextClass, mediaType);
        }
        return false;
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        if (clazz.getName().startsWith(basePackage)) {
            return super.canWrite(clazz, mediaType);
        }
        return false;
    }
}