定制HTTP消息转换器

6 篇文章 0 订阅
1 篇文章 0 订阅

定制HTTP消息转换器

参考文章

将java实体对象转换成HTTP的数据输出流。Spring Boot底层通过HttpMessageConverters依靠Jackson库将Java实体类输出为JSON格式。当有多个转换器可用时,根据消息对象类型和需要的内容类型选择最适合的转换器使用。

基于WebMvcConfigurerAdapter类中的configureMessageConverters方法

import com.aliyun.openservices.shade.com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.openservices.shade.com.alibaba.fastjson.support.config.FastJsonConfig;
import com.aliyun.openservices.shade.com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;

public class BaseWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fjc = new FastJsonConfig();
        //1、序列化重点
        fjc.setSerializerFeatures(SerializerFeature.BrowserCompatible, SerializerFeature.DisableCircularReferenceDetect);
        fastJsonConverter.setFastJsonConfig(fjc);
        converters.add(fastJsonConverter);
    }
}
//作为Springboot启动类 又作为MVC配置类
@SpringBootApplication
@ImportResource("classpath:META-INF/spring/applicationContext.xml") //不要用 *号 保证清晰的引用
public class AppsServerApplication extends BaseWebMvcConfigurerAdapter {

    private static Logger logger = Logger.getLogger(AppsServerApplication.class);

    public static boolean isStartUp = false;


    static public void main(String [] args) {
        isStartUp = false;
        logger.info(">>>>> huduo Apps Server 正在启动 <<<<<");
        SpringApplication.run(AppsServerApplication.class,args);
        logger.info(">>>>> huduo Apps Server 启动完成 <<<<<");
        isStartUp = true;
    }

    /**
     * 配置拦截器
     * @param registry
     */
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CommonInterceptor()).addPathPatterns("/common/**");
        registry.addInterceptor(new CommonInterceptor4User()).addPathPatterns("/common/**");
        //根据不同路径设置不同的拦截器
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //这里可以设置跨域请求,不同路径不同的跨域
    }


}

总结:

  • @ImportResource
  • configureMessageConverters(List<HttpMessageConverter<?>> converters)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值