修改Swagger2ControllerWebMvc 的返回值.

swagger Swagger2ControllerWebMvc 返回值修改

有些场景下相对swagger-doc 返回的文档信息做些增强等. 但pringfox.documentation.swagger.v2.path 无法自定义controller , 所以可以使用切面方式拦截下最后序列化的地方.

序列化


@Aspect
@Component
@AllArgsConstructor
public class SwaggerAspect {

    private final ServerProperties serverProperties;

    @Around("execution(* springfox.documentation.spring.web.json.JsonSerializer.toJson(..))")
    public Object switchDataSource(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (ArrayUtils.isEmpty(args)) {
            return joinPoint.proceed(args);
        }

        String serverIp = "127.0.0.1";
        HttpServletRequest request = getRequest();
        if (request != null) {
            serverIp = request.getHeader("X-GATEWAY-CLIENT-IP");
            //如果是nvriot-saas-uaa需要改成ip ?
            if (StringUtils.isEmpty(serverIp)) {
                //获取本机
                serverIp = NetUtils.localIP() + ":" + serverProperties.getPort();
            }
        }

        String finalServerIp = serverIp;
        Arrays.stream(args)
                .filter(arg -> arg instanceof Swagger)
                .map(arg -> (Swagger) arg)
                .map(Swagger::getPaths)
                .forEach(opMap -> {
                    for (Map.Entry<String, Path> mp : opMap.entrySet()) {
                        Path value = mp.getValue();
                        List<Operation> operations = value.getOperations();
                        for (Operation operation : operations) {
                            //TODO currentIp
                            HeaderParameter headerParameter = new HeaderParameter();
                            headerParameter.setName("server_host");
                            headerParameter.setIn("header");
                            headerParameter.setType("string");
                            headerParameter.setDefault(finalServerIp);
                            value.addParameter(headerParameter);
                            operation.addParameter(headerParameter);
                        }
                    }
                });

        return joinPoint.proceed(args);
    }


    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return (requestAttributes == null) ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
    }
}