JDK动态代理与SpringAop
动态代理
- JDK 动态代理 使用JAVA反射包中的类和接口实现动态代理的功能,JAVA.lang.reflect包;主要是三个类:
InvocationHandler,Method,Proxy;
-
CGLIB动态代理,第三方工具类库,创建代理对象,cglib的原理是继承,通过继承目标类,创建它的子类,在子类中重写父类中同名的方法,实现功能的修改 注意:cglib是继承,重写方法,所以要求目标类不能是final修饰的,方法也不能是final的,cglib的要求目标类比较宽松,只要继承就可以了,cglib在很多的框架中使用,比如mybatis,spring框架中都有使用
JDK动态代理
-
Method类表示方法,目标类的方法;通过Method可以执行某个目标类的方法 Method.invoke(); -
InvocationHandler接口(调用处理器) 就一个方法Invoke方法
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
-
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;
@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);
}
@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) {
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;
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
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;
@Component
@Aspect
public class MybatisAop {
private static final Logger loginfo = LoggerFactory.getLogger(MybatisAop.class);
public static final String POINTCUT_SIGN = "execution(* com.example.demo.mapper..*.*(..)) || " +
"execution(* com.baomidou.mybatisplus.core.mapper..*.*(..))";
@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();
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
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) {
}
}
return result;
}
AopUtils
AOP支持代码的实用方法。 主要用于Spring的AOP支持中的内部使用
@Nullable
public static Object invokeJoinpointUsingReflection(@Nullable Object target, Method method, Object[] args)
throws Throwable {
try {
ReflectionUtils.makeAccessible(method);
return method.invoke(target, args);
}
catch (InvocationTargetException ex) {
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);
}
}
|