1. 使用动态代理实现 AOP
- package com.atguigu.spring.aop;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.Arrays;
- public class ArithmeticCalculatorLoggingProxy {
- // 要代理的对象
- private ArithmeticCalculator target;
- public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
- super();
- this.target = target;
- }
- // 返回代理对象
- public ArithmeticCalculator getLoggingProxy(){
- ArithmeticCalculator proxy = null;
- ClassLoader loader = target.getClass().getClassLoader();
- Class [] interfaces = new Class[]{ArithmeticCalculator.class};
- InvocationHandler h = new InvocationHandler() {
- /**
- * proxy: 代理对象. 一般不使用该对象
- * method: 正在被调用的方法
- * args: 调用方法传入的参数
- */
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- String methodName = method.getName();
- // 打印日志
- System.out.println("[before] The method" + methodName + "begins with" + Arrays.asList(args));
- // 调用目标方法
- Object result = null;
- try {
- // 前置通知
- result = method.invoke(target, args);
- // 返回通知, 可以访问到方法的返回值
- } catch (NullPointerException e) {
- e.printStackTrace();
- // 异常通知, 可以访问到方法出现的异常
- }
- // 后置通知. 因为方法可以能会出异常, 所以访问不到方法的返回值
- // 打印日志
- System.out.println("[after] The method ends with" + result);
- return result;
- }
- };
- /**
- * loader: 代理对象使用的类加载器.
- * interfaces: 指定代理对象的类型. 即代理代理对象中可以有哪些方法.
- * h: 当具体调用代理对象的方法时, 应该如何进行响应, 实际上就是调用 InvocationHandler 的 invoke 方法
- */
- proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
- return proxy;
- }
- }
AOP(Aspect-Oriented Programming, 面向切面编程): 是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充.
AOP 的主要编程对象是切面(aspect), 而切面模块化横切关注点.
在应用 AOP 编程时, 仍然需要定义公共功能, 但可以明确的定义这个功能在哪里, 以什么方式应用, 并且不必修改受影响的类. 这样一来横切关注点就被模块化到特殊的对象 (切面) 里.
AOP 的好处:
每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级
业务模块更简洁, 只包含核心业务代码.
JoinPoint 连接点 指在哪个点触发 某个具体的方法前或者方法后或者发生异常时.
切面: 需要执行的方法的类 @AspectJ
通知: 需要执行的方法
在方法被调用之前需要生成动态代理对象
当 Spring IOC 容器侦测到 Bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理
Spring AOP 学习(五)
来源: http://www.bubuko.com/infodetail-2630000.html