springboot针对controller层返回对象设置全局返回json格式

直接贴代码:

import com.disney.wdpro.service.ecoupon.redemption.service.controller.interceptor.HttpStatusInterceptor;
import com.disney.wdpro.service.ecoupon.redemption.service.controller.interceptor.OpenapiInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class ConfigInterceptor implements WebMvcConfigurer {

    @Bean("httpStatusInterceptor")
    public HttpStatusInterceptor getHttpStatusInterceptor() {
        return new HttpStatusInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getHttpStatusInterceptor()).addPathPatterns("/**");
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.ignoreAcceptHeader(true)  // 这里一定要设置为true,才能覆盖原来的默认的xml format
                .defaultContentType(MediaType.APPLICATION_JSON);
    }
}

 

 

end.

posted on 2020-09-08 10:55  梦幻朵颜  阅读(2887)  评论(0编辑  收藏  举报