目标: 11-Spring-AOP-通过案例理解AOP这篇文章中是一个简单的实现JDK代理的功能,需要完善工具包(LogUtils)和代理操作(JDKProxyHandler).
掌握1: 日志工具类中日志的四个阶段(logBefore,logAfter,logThrowing,logAfterReturing)
掌握2: 代理操作实现日志记录的步骤
计数功能加日记功能优化代码
// logUtils.java(top.starrylsi.utils)
package top.starrylsi.utils;
import java.util.Arrays;
public class LogUtils {
//1.执行前
public static void logBefore(String method,Object ...params) {
System.out.println("这是"+method+"方法"+"参数:"+Arrays.toString(params));
}
//2.执行完毕
public static void logAfter(String method) {
System.out.println("这是"+method+"方法"+"方法执行完毕");
}
//3.执行异常
public static void logThrowing(String method,Exception e) {
System.out.println("这是"+method+"方法抛出了异常 异常是:"+e.getMessage());
}
//4.返回结果
public static void logAfterReturing(String method,Object result) {
System.out.println("这是"+method+"方法: 结果是:"+result);
}
}
// JDKProxyHandler(top.starrylsi.proxy)
package top.starrylsi.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import top.starrylsi.caculate.Caculate;
import top.starrylsi.utils.LogUtils;
public class JDKProxyHandler implements InvocationHandler{
private Caculate caculate;
public JDKProxyHandler(Caculate caculate) {
this.caculate = caculate;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//1. 获取方法名
String methodName = method.getName();
//2. 调用日志
LogUtils.logBefore(methodName, args);
//3. 声明结果
Object result =null;
//4. 执行方法 并获取返回值
try {
result = method.invoke(caculate, args);
} catch (Exception e) {
//5. 出异常显示异常日志
LogUtils.logThrowing(methodName, e);
}finally {
//6.执行日志完毕
LogUtils.logAfter(methodName);
}
if(result != null) {
LogUtils.logAfterReturing(methodName, result);
}
return null;
}
}
评论 (0)