AOP和动态代理-自定义注解切入使用-01

JDK动态代理与SpringAop

动态代理

  1. JDK 动态代理 使用JAVA反射包中的类和接口实现动态代理的功能,JAVA.lang.reflect包;主要是三个类:

InvocationHandler,Method,Proxy;

  1. CGLIB动态代理,第三方工具类库,创建代理对象,cglib的原理是继承,通过继承目标类,创建它的子类,在子类中重写父类中同名的方法,实现功能的修改

    注意:cglib是继承,重写方法,所以要求目标类不能是final修饰的,方法也不能是final的,cglib的要求目标类比较宽松,只要继承就可以了,cglib在很多的框架中使用,比如mybatis,spring框架中都有使用

JDK动态代理

  1. Method类表示方法,目标类的方法;通过Method可以执行某个目标类的方法 Method.invoke();

  2. InvocationHandler接口(调用处理器) 就一个方法Invoke方法

public Object invoke(Object proxy, Method method, Object[] args)
 throws Throwable;
  1. Proxy类:核心的对象 创建代理对象

    @param ClassLoader 目标类加载器 getClass().getClassLo ader()

    @param interfaces 接口 目标类实现的接口 也是反射获取的

    @param InvocationHandler 代理类要完成的功能 我们自己写的

    @return 目标对象的代理对象

public static Object newProxyInstance(ClassLoader loader,
                                   Class<?>[] interfaces,
                                   InvocationHandler h){}

AOP

Demo 日志简单切面
package com.example.demo.aspect;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.annotation.Log;
import com.example.demo.entity.Logs;
import com.example.demo.enums.BusinessStatus;
import com.example.demo.service.LogsService;
import com.example.demo.utils.IpUtils;
import com.example.demo.utils.RedisService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author JFCODER
 * @date 2022/5/29
 * @description 日志类
 */

@Component
@Aspect
public class DBLogsAop {

    @Autowired
    private LogsService logsService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisService redisService;

    private static final Logger loginfo = LoggerFactory.getLogger(DBLogsAop.class);

    @Before("@annotation(log)")
    public void beforeRuning(JoinPoint joinPoint, Log log) throws Throwable {
        loginfo.info("==========前置通知=============");
        if (redisReduce(request)) {
            loginfo.warn("==========请求成功=============");
        } else {
            loginfo.error("频繁请求");
            throw new Throwable();
        }
    }

    private boolean redisReduce(HttpServletRequest request) {
        String ip = IpUtils.getIpAddr(request);
        String id = request.getSession().getId();
        String key = "AOP:KEY" + ip.concat(id);

        if (redisService.hasKey(key)) {
            return false;
        } else {
            redisService.setCacheObject(key, ip, 10L, TimeUnit.SECONDS);
            return true;
        }
    }


    @AfterReturning(pointcut = "@annotation(log)", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Log log, Object result) {
        handleLog(joinPoint, log, null, result);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(log)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log log, Exception e) {
        handleLog(joinPoint, log, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, Log log, final Exception e, Object result) {
        /*日志信息收集*/
        Logs logs = new Logs();
        try {

            String ip = IpUtils.getIpAddr(request);
            logs.setIp(ip);
            logs.setUrl(request.getRequestURI());
            logs.setCode(BusinessStatus.SUCCESS.toString());
            if (e != null) {
                logs.setCode(BusinessStatus.FAIL.toString());
            }
            Object[] args = joinPoint.getArgs();
            if (args.length > 0) {
//                SourceLocation sourceLocation = joinPoint.getSourceLocation();
//                if (sourceLocation != null) {
//                    System.out.println(sourceLocation.getWithinType());
//                    System.out.println(sourceLocation.getFileName());
//                }
                System.out.println(joinPoint.getSignature());
                System.out.println(joinPoint.getTarget());
                StringBuilder buffer = new StringBuilder();
                for (Object arg : args) {
                    buffer.append(arg);
                }
                logs.setContent(buffer.toString());
            }

        } catch (Exception exception) {
            logs.setCode(BusinessStatus.FAIL.toString());
            exception.printStackTrace();
        } finally {
            logsService.saveLogs(logs);
        }
    }

}

package com.example.demo.annotation;

import com.example.demo.enums.BusinessStatus;
import com.example.demo.enums.BusinessType;
import com.example.demo.enums.OperatorType;

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

/**
 * @author JFCODER
 * @date 2022/5/29
 * @description 请求日志注解
 */
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    /**
     * 请求url
     * */
    public String url() default "";

    /**
     * 功能
     * */
    public BusinessType businessType() default BusinessType.OTHER;


    /**
     * 操作人类别
     */
    public OperatorType operatorType() default OperatorType.MANAGE;

    /**
     * 操作状态
     */
    public BusinessStatus businessStatus() default BusinessStatus.FAIL;


}

在这里插入图片描述

DEMO 动态代理跟AOP的使用
package com.example.demo.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author JFCODER
 * @date 2022/5/29
 * @description 自定义切换mapper执行方法
 */
@Component
@Aspect
public class MybatisAop {

    private static final Logger loginfo = LoggerFactory.getLogger(MybatisAop.class);


    /**
     * 定义AOP签名 (切入所有使用的方法)
     */
    public static final String POINTCUT_SIGN = "execution(* com.example.demo.mapper..*.*(..)) || " +
            "execution(* com.baomidou.mybatisplus.core.mapper..*.*(..))";

    /**
     * 声明AOP签名
     */
    @Pointcut(POINTCUT_SIGN)
    public void pointcut() {
    }


    @Around("pointcut()")
    public Object switchMethod(ProceedingJoinPoint point) throws Throwable {

        System.out.println("我是环绕通知前....");
        //执行目标函数
        MethodSignature signature =(MethodSignature) point.getSignature();
        Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
        /*如果是getAllA方法 则调用getAllB*/
        if (signature.getMethod().getName().contains("getAllA")) {
            Method method = point.getTarget().getClass().getMethod("getAllB", parameterTypes);
            return AopUtils.invokeJoinpointUsingReflection(point.getTarget(), method, point.getArgs());
        }
        System.out.println("我是环绕通知后....");

        return point.proceed();
    }
}

关于Spring提供的动态代理反射和AOP工具类

ReflectUtils

	// used by MethodInterceptorGenerated generated code
	public static Method[] findMethods(String[] namesAndDescriptors, Method[] methods) {
		Map map = new HashMap();
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			map.put(method.getName() + Type.getMethodDescriptor(method), method);
		}
		Method[] result = new Method[namesAndDescriptors.length / 2];
		for (int i = 0; i < result.length; i++) {
			result[i] = (Method) map.get(namesAndDescriptors[i * 2] + namesAndDescriptors[i * 2 + 1]);
			if (result[i] == null) {
				// TODO: error?
			}
		}
		return result;
	}
AopUtils

AOP支持代码的实用方法。 主要用于Spring的AOP支持中的内部使用

	/**
   作为AOP方法调用的一部分,通过反射调用给定的目标。
    参数: target–目标对象 method–要调用的方法     
    args–方法的参数 返回值: 调用结果(如果有) 
    抛出: Throwable–如果由目标方法抛出 AOPINotationException–
    在反射错误的情况下 reflection error
	 */
	@Nullable
	public static Object invokeJoinpointUsingReflection(@Nullable Object target, Method method, Object[] args)
			throws Throwable {

		// Use reflection to invoke the method.
		try {
			ReflectionUtils.makeAccessible(method);
			return method.invoke(target, args);
		}
		catch (InvocationTargetException ex) {
			// Invoked method threw a checked exception.
			// We must rethrow it. The client won't see the interceptor.
			throw ex.getTargetException();
		}
		catch (IllegalArgumentException ex) {
			throw new AopInvocationException("AOP configuration seems to be invalid: tried calling method [" +
					method + "] on target [" + target + "]", ex);
		}
		catch (IllegalAccessException ex) {
			throw new AopInvocationException("Could not access method [" + method + "]", ex);
		}
	}

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

JF Coder

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

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

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

打赏作者

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

抵扣说明:

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

余额充值