微服务多模块架构下统一封装返回值格式

项目场景:

在做谷粒商城项目时,想优化一下结果集封装,不想每个接口在返回数据时都要手动用R封装结果集。想到用实现ResponsebodyAdvice接口在数据返回到前台之前用aop统一用R类封装结果集的方法实现。这个方法每个业务模块都要使用,如果每个模块都实现这样的一个类代码会冗余。因此打算将这个实现类放在common模块,然后所有模块引用common。这样这个类就能在所有引用了common模块的业务模块生效。


问题描述

首先定义一个类实现ResponseBodyAdvice接口,重写两个方法。这个类中主要是对返回的数据进行处理,底层实现原理为aop。也可以在这个类里面对异常进行处理,实现异常处理器即可。

package com.xiayuchen.common.advice;

import com.xiayuchen.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.xiayuchen")
public class MallResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }
    public static final Logger log = LoggerFactory.getLogger(MallResponseBodyAdvice.class);

    //参数校验异常处理器
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result argumentValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("出现异常:{},异常类型", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(data -> {
            errorMap.put(data.getField(), data.getDefaultMessage());
        });
        return Result.fail(errorMap, e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error("出现异常:{},异常类型", e.getMessage(), e.getClass());
        return Result.fail(null, e.getMessage());
    }

    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof String) {
            return Result.success((String) o);
        } else if (o instanceof Exception) {
            return Result.fail(null, ((Exception) o).getMessage());
        } else if (o instanceof Result) {
            return o;
        }
        return Result.success(o);
    }
}

但重启后发现即使是引用了common模块的其他模块的接口返回值并没有被封装成统一格式。也就是说该类在其他模块没有生效。

原因分析:

每个模块的启动类在启动时默认只扫描本模块下的类,因此默认是扫描不到common模块中的类,也无法将common中的类加入ioc容器。


解决方案:

在想使用该类进行结果集统一封装的模块的启动类上使用@ComponentScans或@ComponentScan注解手动指定路径。

@SpringBootApplication
//开启nacos
@EnableDiscoveryClient
//开启feign远程调用并指定远程调用接口包的路径
@EnableFeignClients(basePackages = "com.xiayuchen.mall.member.feign")
@ComponentScans(value = {@ComponentScan(basePackages = "com.xiayuchen.common")})
public class MallMemberApplication {

    public static void main(String[] args) {
        SpringApplication.run(MallMemberApplication.class, args);
    }

}```



  • 14
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值