SpringAop自定义切面注解、自定义过滤器及ThreadLocal详解

 更新时间:2024年01月10日 10:38:13   作者:苦糖果与忍冬  
这篇文章主要介绍了SpringAop自定义切面注解、自定义过滤器及ThreadLocal详解,Aspect(切面)通常是一个类,里面可以定义切入点和通知(切面 = 切点+通知),execution()是最常用的切点函数,需要的朋友可以参考下

一、切面表达式

execution()是最常用的切点函数,其语法如下所示:

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern) throws-pattern?)

execution(<修饰符模式>? <返回类型模式><声明类型模式><方法名模式>(<参数模式>) <异常模式>?) 除了返回类型模式、方法名模式和参数模式外,其它项都是可选的

返回类型模式确定方法的返回类型必须是什么,以便匹配连接点。*最常用作返回类型模式。它匹配任何返回类型。只有当方法返回给定类型时,完全限定的类型名称才匹配。

参数模式稍微复杂一些:

()匹配一个不带参数的方法,而(..)匹配任意数量(零个或更多)的参数。

(*)模式匹配采用任意类型的一个参数的方法。(*,String)匹配采用两个参数的方法。第一个可以是任何类型,而第二个必须是字符串。

二、实战代码

Controller

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.CustomizableThreadCreator;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/controller")
public class TestController implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    @GetMapping("/test")
    public String test(@RequestParam String name){
        System.out.println("TestController请求进来了:"+Thread.currentThread().getName());
        TestEvent event = new TestEvent(this,name);
//        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
//        for (int i = 0; i <beanDefinitionNames.length ; i++) {
//            System.out.println(beanDefinitionNames[i]);
//        }
        applicationEventPublisher.publishEvent(event);
        System.out.println("TestController请求出去了:"+Thread.currentThread().getName());
        CustomizableThreadCreator bean = applicationContext.getBean(CustomizableThreadCreator.class);
        System.out.println("CustomizableThreadCreator:"+bean.getThreadNamePrefix());
        return "success";
    }
    @PostMapping("/test2")
    @LogAespect
    public String test2(@RequestBody TestRequest request){
        System.out.println("TestController请求进来了:"+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
            System.out.println("hobby:"+request.getHobby());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("TestController请求出去了:"+Thread.currentThread().getName());
        return "success";
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        TestController.applicationContext=applicationContext;
    }
}

定义切面

常用的两种:一种是基于表达式,另一种是基于注解的。

注解十分灵活,所以编程中使用的较多。在你需要拦截的方法上面加上自定义注解@LogAespect即可。

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class TestAspect {
    @Pointcut("execution(public * com.test.realname.controller.TestController.test(..))")
    public void pointCut(){
        //这里一般无实际意义
    }
    @Before("pointCut()")
    public void before()
    {
        System.out.println("===before====");
    }
    @AfterReturning("pointCut()")
    public void afterReturning()
    {
        System.out.println("===afterReturning===");
    }
    @Around("@annotation(com.test.realname.controller.LogAespect)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long l = System.currentTimeMillis();
        HttpServletRequest request = MyFilter.CURRENT_REQUEST.get();
        String requestURI = request.getRequestURI();
        Object proceed = joinPoint.proceed();
        String s=null;
        if(proceed instanceof String){
            s = (String) proceed;
        }
        System.out.println("请求路径"+requestURI);
        System.out.println("响应"+s);
        System.out.println("cost time"+(System.currentTimeMillis()-l));
        return proceed;
    }
}

定义切面注解

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)
public @interface LogAespect {
}

request

import java.io.Serializable;

public class TestRequest implements Serializable {

    private String hobby;
    private String streamNo;

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String getStreamNo() {
        return streamNo;
    }

    public void setStreamNo(String streamNo) {
        this.streamNo = streamNo;
    }

    @Override
    public String toString() {
        return "TestRequest{" +
                "hobby='" + hobby + '\'' +
                ", streamNo='" + streamNo + '\'' +
                '}';
    }
}

request请求中的RequestBody只能读取一次,因为RequestBody是流ServletInputStream,只能读取一次,所以需要对request请求进行包装,使其能多次重复读取。

import org.springframework.util.StreamUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class HttpRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] body;
    public HttpRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body= StreamUtils.copyToByteArray(request.getInputStream());
    }
    @Override
    public BufferedReader getReader() throws IOException{
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
    @Override
    public ServletInputStream getInputStream() throws IOException{
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }
}

自定义过滤器,将request缓存到ThreadLocal中,方便在切面中使用。

ThreadLocal记得在finally中清空,防止内存泄漏。

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Component
public class MyFilter extends OncePerRequestFilter {
    public static final ThreadLocal<HttpServletRequest> CURRENT_REQUEST = new ThreadLocal<>();
    public static boolean isJsonRequest(HttpServletRequest request){
        if(request==null){
            return false;
        }
        return StringUtils.contains(request.getContentType(),"json");
    }
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        boolean jsonRequest = isJsonRequest(httpServletRequest);
        try {
            if(jsonRequest){
                HttpRequestWrapper wrapper = new HttpRequestWrapper(httpServletRequest);
                CURRENT_REQUEST.set(wrapper);
                String s = StreamUtils.copyToString(wrapper.getInputStream(), StandardCharsets.UTF_8);
                Map map = JSON.parseObject(s, Map.class);
                System.out.println(map);
                filterChain.doFilter(wrapper,httpServletResponse);
            }else {
                CURRENT_REQUEST.set(httpServletRequest);
                filterChain.doFilter(httpServletRequest,httpServletResponse);
            }
        }finally {
            CURRENT_REQUEST.remove();
        }
    }
}

正常返回

{hobby=ball}
TestController请求进来了:http-nio-8080-exec-1
hobby:ball
TestController请求出去了:http-nio-8080-exec-1
请求路径/controller/test2
响应success
cost time1009

如果取消包装的话,就会直接报错

{hobby=ball} 2023-01-03 15:45:31.664 WARN 13596 — [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.test.realname.controller.TestController.test2(com.test.realname.controller.TestRequest)]

到此这篇关于SpringAop自定义切面注解、自定义过滤器及ThreadLocal详解的文章就介绍到这了,更多相关SpringAop自定义切面注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Quarkus篇入门创建项目搭建debug环境

    Quarkus篇入门创建项目搭建debug环境

    这篇文章主要为大家介绍了Quarkus篇入门创建项目搭建debug环境,先来一套hello world,来搭建基本的运行及调试环境吧
    2022-02-02
  • Spring Boot集成Redis实战操作功能

    Spring Boot集成Redis实战操作功能

    这篇文章主要介绍了Spring Boot集成Redis实战操作,包括如何集成redis以及redis的一些优点,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-11-11
  • 多模块maven的deploy集成gitlab ci自动发版配置

    多模块maven的deploy集成gitlab ci自动发版配置

    这篇文章主要为大家介绍了多模块maven项目deploy集成gitlab ci自动发版的配置流程步骤,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2022-02-02
  • 大数组元素差异removeAll与Map效率对比

    大数组元素差异removeAll与Map效率对比

    这篇文章主要介绍了大数组元素差异removeAll与Map效率对比,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • java简单解析xls文件的方法示例【读取和写入】

    java简单解析xls文件的方法示例【读取和写入】

    这篇文章主要介绍了java简单解析xls文件的方法,结合实例形式分析了java针对xls文件的读取和写入相关操作技巧与注意事项,需要的朋友可以参考下
    2017-06-06
  • Java中的MapStruct实现详解

    Java中的MapStruct实现详解

    这篇文章主要介绍了Java中的MapStruct实现详解,MapStruct 是一个代码生成器,它基于约定优先于配置的方法大大简化了 JavaBean 类型之间映射的实现,生成的映射代码使用普通方法调用,需要的朋友可以参考下
    2023-11-11
  • Spring 自动装配的二义性实例解析

    Spring 自动装配的二义性实例解析

    这篇文章主要介绍了Spring 自动装配的二义性实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Struts 2 数据校验功能及校验问题的解决方案

    Struts 2 数据校验功能及校验问题的解决方案

    这篇文章主要介绍了Struts 2 数据校验功能及校验问题的解决方案的相关资料,需要的朋友可以参考下
    2016-09-09
  • Response如何实现重定向

    Response如何实现重定向

    这篇文章主要介绍了Response如何实现重定向方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • Java泛型通配符的使用详解

    Java泛型通配符的使用详解

    本文主要介绍了Java泛型通配符的使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01

最新评论