springboot2.x对controller的响应结果进行注解处理(即切面处理)

1.需求

需要针对某些Controller的返回结果进行统一的处理,类似记录日志或者干嘛,使用注解最为方便,下面使用注解解决这个需求.

2.实现思路

写个注解,在注解内进行业务逻辑处理,所有上面加了这个注解的方法都可以通过这个注解的功能做一些自定义的业务逻辑.

3.代码

3.1.配置文件增加开关

# 注解启用的开关
anno-xxx:
  open: true

3.2.配置读取类

package xxx;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 分级授权配置文件(对应yml)
 */
@ConfigurationProperties(prefix = "anno-xxx")
public class XxxProperties {

    /**
     * 开启调试模式(或者开关),用于像Swagger这种在线API测试场景
     */
    private boolean open;

    public boolean isOpen() {
        return open;
    }

    public void setOpen(boolean open) {
        this.open = open;
    }
}

3.3.定义一个注解

package xxx;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 分级授权注解定义
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Xxx{
}

3.4.启用注解自动配置

package xxx;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * 分级授权开启注解自动配置
 */
@Configuration
@Component
@EnableAutoConfiguration
@EnableConfigurationProperties(XxxProperties.class)
public class XxxAutoConfiguration {
}

3.5.注解实现类内写业务逻辑

package xxx;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 请求响应处理类 对加了@Xxx注解的方法的数据进行分级授权筛选
 */
@Slf4j
@ControllerAdvice
public class ClassifiedAuthResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private ClassifiedAuthProperties properties;
    private static ThreadLocal<Boolean> encryptLocal = new ThreadLocal<Boolean>();

    public static void setStatus(boolean status){
        encryptLocal.set(status);
    }

    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    /**
     * 切面主要处理入口,针对响应报文进行处理
     */
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        //可以通过调用XxxResponseBodyAdvice.setStatus(false)来动态设置不操作
        Boolean status = encryptLocal.get();
        if (status != null && status == false){
            encryptLocal.remove();
            return body;
        }
        long start = System.currentTimeMillis();
        boolean doIt = false;
        if (returnType.getMethod().isAnnotationPresent(ClassifiedAuth.class) && properties.isOpen()){
            doIt = true;
        }
        if (doIt){
            //开始业务处理
            JSONObject jsonObject = JSONObject.from(body);
            //TODO 筛选逻辑
            jsonObject.replace("data",null);
            jsonObject.replace("msg","暂无权限");
            body = jsonObject;
        }
        long end = System.currentTimeMillis();
        log.info("Xxx处理耗时={}ms", (end-start));
        return body;
    }
}

4.注解使用

//...
@ApiOperation("Xxx接口")
@PostMapping("/xxx")
@Xxx //在这里使用Xxx注解,即可完成此类方法的处理
public Object doSth(@RequestBody Vo vo)
{
    return xxxService.doSthXxx(vo);
}
//...
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cgv3

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值