Java代理模式及spring aop实现原理

spring AOP是什么?

传统的OOP的编程中,http请求通过servlet,service,dao是一层一层的,代码逻辑是自上而下的,但是在自上而下的过程中,比如在service的login方法中需要记录日志,而在login方法的dao层需要记录查询的时间,这些就是一些横切面的问题,因为它与我们的主业务逻辑关系不大,并且它会在每个业务逻辑都需要写上同样的代码,导致代码难以维护。AOP的思想就是把业务逻辑和横切面进行分离,提高了代码的重用性,降低了耦合性使维护简单,提高了开发效率。

应用场景:

  1. 日志记录
  2. 权限验证
  3. 效率检查
  4. 事务管理

注解:

  • @Aspect:表示这是切面
  • @Pointcut:切点
  • @JointPoint:连接点目标对象中的方法
  • @Advice:
    • @Before
    • @After
    • @AfterThrowing
    • @Aroud
    • @AfterReturning

JoinPoint中基本API操作

@Aspect
@Component
public class aopAspect {
    /**
     * 定义一个切入点表达式,用来确定哪些类需要代理
     * execution(* aopdemo.*.*(..))代表aopdemo包下所有类的所有方法都会被代理
     */
    @Pointcut("@annotation(com.mytest.test.annoation.Logs)")
    public void declareJoinPointerExpression() {}

    /**
     * 前置方法,在目标方法执行前执行
     * @param joinPoint 封装了代理方法信息的对象,若用不到则可以忽略不写
     */
    @Before("declareJoinPointerExpression()")
    public void beforeMethod(JoinPoint joinPoint){
        System.out.println("目标方法名为:" + joinPoint.getSignature().getName());
        System.out.println("目标方法所属类的简单类名:" +        joinPoint.getSignature().getDeclaringType().getSimpleName());
        System.out.println("目标方法所属类的类名:" + joinPoint.getSignature().getDeclaringTypeName());
        System.out.println("目标方法声明类型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
        //获取传入目标方法的参数
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            System.out.println("第" + (i+1) + "个参数为:" + args[i]);
        }
        System.out.println("被代理的对象:" + joinPoint.getTarget());
        System.out.println("代理对象自己:" + joinPoint.getThis());
    }

    /**
     * 环绕方法,可自定义目标方法执行的时机
     * @param pjd JoinPoint的子接口,添加了
     *            Object proceed() throws Throwable 执行目标方法
     *            Object proceed(Object[] var1) throws Throwable 传入的新的参数去执行目标方法
     *            两个方法
     * @return 此方法需要返回值,返回值视为目标方法的返回值
     */
    @Around("declareJoinPointerExpression()")
    public Object aroundMethod(ProceedingJoinPoint pjd){
        Object result = null;

        try {
            //前置通知
            System.out.println("目标方法执行前...");
            //执行目标方法
            //result = pjd.proeed();
            //用新的参数值执行目标方法
            result = pjd.proceed();
            //返回通知
            System.out.println("目标方法返回结果后...");
        } catch (Throwable e) {
            //异常通知
            System.out.println("执行目标方法异常后...");
            throw new RuntimeException(e);
        }
        //后置通知
        System.out.println("目标方法执行后...");

        return result;
    }
}

如果用了around注解后,需要调用proceedingJoinPoint.proceed()方法才会执行接口中的代码,同时@Before才会执行,否则不会执行,但是@After方法都会执行

ProceedingJoinPoint定义了两个方法,一个是proceed()直接执行,参数为默认的即接口中传入的参数,一个重载的方法,可以自定义参数

            User user = new User();
            user.setName("lihc");
            Object[] obj = {user};
            result = pjd.proceed(obj);

打印结果:

目标方法执行前...
目标方法名为:test
目标方法所属类的简单类名:TestController
目标方法所属类的类名:com.mytest.test.controller.TestController
目标方法声明类型:public1个参数为:User(name=牟野, id=0, age=0)
被代理的对象:com.mytest.test.controller.TestController@248d9e8f
代理对象自己:com.mytest.test.controller.TestController@248d9e8f
这是接口中打印的
目标方法返回结果后...
目标方法执行后...

获取方法中的注解方法

    private SysUserOperLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(SysUserOperLog.class);
        }
        return null;
    }

然后通过注解点属性的方式,可以直接获取到我们在注解里定义的属性

代理模式

什么是代理模式?

代理模式意思是,给原有对象提供一个代理对象,我们通过代理对象来控制对原有对象的访问。可以理解为代替处理,由代理对象代理原对象处理某些逻辑。以房产中介举例,我们直接通过中介来租房子,而绕开了房东本人,此例中,房东是原有对象,中介就是代理对象,房子就是对象中的属性或方法。

作用:

  1. 不修改原对象代码的基础上,对原对象功能加强。
  2. 提高了代码的重用性,降低了耦合性使维护简单,提高了开发效率

静态代理

第一种方式:实现同一个接口

定义接口

public interface AgentInterface {
    void order(String foodName);
}

原对象

public class Customer implements AgentInterface {
    @Override
    public void order(String foodName) {
        System.out.println("点餐名字"+foodName);
    }
}

代理对象

public class DeliverAgent implements AgentInterface {
    private Customer customer;

    DeliverAgent(Customer customer) {
        this.customer = customer;
    }
    @Override

    public void order(String foodName) {
        customer.order(foodName);
        //模拟派送业务
        System.out.println("处理派送业务");
    }
}

测试:

public class Test {
    public static void main(String[] args) {
        Customer customer = new Customer();
        DeliverAgent deliverAgent = new DeliverAgent(customer);
        String foodName = "红烧肉";
        customer.order(foodName);
        System.out.println("*********************");
        deliverAgent.order(foodName);
    }
}

打印结果:

点餐名字红烧肉
*********************
点餐名字红烧肉
处理派送业务

这里可以看到DeliverAgent作为Customer的代理对象,对原对象的功能进行了增强,但是这种方法并不适合在实际开发中使用,因为需要写很多的代理对象,背离了我们的初衷。

第二种方式:代理对象继承原对象

原对象

public class Customer  {
    public void order(String foodName) {
        System.out.println("点餐名字"+foodName);
    }
}

代理对象,继承原对象

public class DeliverAgent extends Customer {
    private Customer customer;

    DeliverAgent(Customer customer) {
        this.customer = customer;
    }
    @Override

    public void order(String foodName) {
        customer.order(foodName);
        //模拟派送业务
        System.out.println("处理派送业务");
    }
}

测试:

public class Test {
    public static void main(String[] args) {
        Customer customer = new Customer();
        DeliverAgent deliverAgent = new DeliverAgent(customer);
        String foodName = "红烧肉";
        customer.order(foodName);
        System.out.println("*********************");
        deliverAgent.order(foodName);
    }
}

打印:

点餐名字红烧肉
*********************
点餐名字红烧肉
处理派送业务

可以看到这里和实现同一个接口的方式打印结果是一样的,也对原对象功能进行了增强,但是也是要写很多类,太麻烦。

动态代理

jdk动态代理

jdk自带的动态代理技术,需要使用一个静态方法(Proxy.newProxyInstance)来创建代理对象,它要求原对象(被代理对象),必须实现接口,这样生成的代理对象和原对象都会实现相同的接口,类似静态代理中实现相同接口的方案。

    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
  • ClassLoader loader:固定写法,指定目标类对象的类加载器,用于加载目标类及其接口的字节码文件。
  • Class<?>[] interfaces:固定写法,指定目标类实现的所有接口的字节码对象的数组,通常使用目标类的字节码对象调用getInterfaces()方法即可。
  • InvocationHandler h:这是一个接口,主要关注它里面唯一的一个方法,invoke,它会在代理类对象调用方法时执行,也就是说,我们在代理类中调用任何方法时,都会执行invoke方法。所以我们是在此方法中完成了对代码增强或扩展代码逻辑的编写。
    • public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable;
      

proxy:就是代理类对象的一个引用,也就是Proxy.newProxyInstance的返回值,几乎不会用到,忽略。
method:对应的是触发invoke执行的method对象,比如我们调用了xx方法,改方法触发了invoke执行,那么,method就是xx方法对应的反射对象(method)。
args:代理对象调用方法时,传递进来的实际参数。

接口:

public interface AgentInterface {
    String order(String foodName);

    void test();

    void test2();
}

原对象,实现了上面接口:

public class Customer implements AgentInterface {
    @Override
    public String order(String foodName) {
        return foodName;
    }

    @Override
    public void test() {

    }

    @Override
    public void test2() {

    }
}

测试:

    public static void main(String[] args) {
        Customer customer = new Customer();
        AgentInterface proxyInstance = (AgentInterface) Proxy.newProxyInstance(customer.getClass().getClassLoader(),
                customer.getClass().getInterfaces(),
                //Lambda表达式
                (proxy, method, arg) -> {
                    if ("order".equals(method.getName())) {
                        System.out.println("在目标方法前执行增强逻辑");
                        Object result = method.invoke(customer, arg);
                        System.out.println("在目标方法后执行增强逻辑");
                        return result + "-增强过后";
                    } else {
                        return method.invoke(customer, arg);
                    }
                });
        //String order = proxyInstance.order("红烧肉");
        //System.out.println(order);
        proxyInstance.test();
    }

proxyInstance.order(“红烧肉”)打印结果:

代理对象执行
执行增强逻辑
红烧肉-增强过后

proxyInstance.test()没有输出任何语句,因为test方法本身无方法实体,而且在method.invoke方法里面做了判断,在方法名是order时才会执行增强逻辑。

模拟Proxy.newProxyInstance方法在底层如何通过jdk动态代理实现动态代理的

接口:

public interface AgentInterface {
    String order(String foodName);

    void test();

    void test2();
}

原对象:

public class Customer implements AgentInterface {
    @Override
    public String order(String foodName) {
        return foodName;
    }

    @Override
    public void test() {

    }

    @Override
    public void test2() {

    }
}

模拟jdk动态代理生成的代理对象:

/**
 * 此处模拟Proxy.newProxyInstance方法在底层如何通过jdk动态代理实现动态代理的
 */
public class AgentCustomer implements AgentInterface {

    private InvocationHandler invocationHandler;

    AgentCustomer(InvocationHandler invocationHandler) {
        this.invocationHandler = invocationHandler;
    }

    @Override
    public String order(String foodName) {
        //每个方法的实现直接调用InvocationHandler的invoke方法,调用了原对象中的方法,并执行了增强方法
        try {
            //调用的是order方法,通过反射获取order方法的Method对象,传入invoke中
            Method method = AgentInterface.class.getMethod("order", String.class);
            String result = (String)invocationHandler.invoke(this, method, new Object[]{foodName});
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    @Override
    public void test() {
        //每个方法的实现直接调用InvocationHandler的invoke方法,调用了原对象中的方法,并执行了增强方法
        try {
            //调用的是test方法,通过反射获取test方法的Method对象,传入invoke中
            Method method = AgentInterface.class.getMethod("test", String.class);
            //没有返回值,所以返回null
            invocationHandler.invoke(this, method, null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    @Override
    public void test2() {
        //每个方法的实现直接调用InvocationHandler的invoke方法,调用了原对象中的方法,并执行了增强方法
        try {
            //调用的是test2方法,通过反射获取test2方法的Method对象,传入invoke中
            Method method = AgentInterface.class.getMethod("test2", String.class);
            //没有返回值,所以返回null
            invocationHandler.invoke(this, method, null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}

测试:

这里创建了InvocationHandler接口的实现类,还有原对象的实现类,将他们两个都传入代理对象中,调用代理对象方法时会执行invoke方法(即调用并执行了原对象的方法),然后可以在invoke方法前后执行增强方法,即实现了aop功能增强。

public class Test {
    public static void main(String[] args) {
        Customer customer = new Customer();
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("order".equals(method.getName())) {
                    System.out.println("模拟操作之前增强方法");
                    String result = (String) method.invoke(customer,args);
                    System.out.println("模拟操作之后增强方法");
                    return result;
                } else {
                    return method.invoke(customer, args);
                }
            }
        };
        AgentCustomer agentCustomer = new AgentCustomer(invocationHandler);
        String order = agentCustomer.order("红烧肉");
        System.out.println(order);
    }
}

基于接口的动态代理,实际上是在内存中生成了一个代理对象,这个代理对象实现了原对象相同的接口,类似静态代理中两个对象实现了相同的接口,然后在代理对象中实现了功能增强。

原对象和代理对象是兄弟关系,那么我们的代理对象就不能强转为原对象,在spring中如果使用了jdk动态代理,需要使用接口类型来接收代理对象。

cglib动态代理

cglib是第三方库,通过继承目标类(原对象)的方式实现动态代理,所以就要求这个类不能被final修饰,但它不要求这个类继承一个接口.

使用Enhancer.create(Class type, Callback callback)实现动态代理,create方法:

public static Object create(Class type, Callback callback)
  • Class type:指定我们要代理的目标类的字节码对象,也就是目标类的类型。
  • Callback callback:单词意思为回调,意思是我们提供一个方法,它会在合适的时候帮我们调用它,即回来调用的意思。一般情况下,使用的是它的子接口MethodInterceptor,其接口只有一个方法intercept需要我们实现。
 Object intercept(Object var1, Method var2, Object[] var3, MethodProxy var4) throws Throwable;
  • Object:就是我们代理类对象的一个引用,也就是Enhancer.create方法的返回值,此引用几乎用不到,忽略。
  • Method:对应的触发intercept执行的方法的Method对象,假如我们调用了XXX方法,该方法触发了intercept的执行,那么,method就是XXX方法对应的反射对象。
  • Object[]:代理对象调用方法时,传递的实际参数。
  • MethodProxy:方法的代理对象,一般也不做处理,忽略。

原对象:

public class Customer {
    public String order(String foodName) {
        return foodName;
    }
    
    public void test() {
        
    }
}

测试:

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Customer customer = new Customer();
        Customer agentCustomer = (Customer)Enhancer.create(Customer.class, new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                if ("order".equals(method.getName())) {
                    System.out.println("模拟方法钱增强方法");
                    Object result = method.invoke(customer, args);
                    System.out.println("模拟方法后增强方法");
                    return result + "增强后";
                } else {
                    return method.invoke(customer, args);
                }
            }
        });
        String result = agentCustomer.order("红烧肉");
        System.out.println(result);
    }
}

打印结果:

模拟方法前增强方法
模拟方法后增强方法
红烧肉增强后

基于cglib继承父类的方法的动态代理,是在内存中生成了一个代理对象,这个对象继承了原对象(目标类),类似静态代理中继承的方式,目标类和代理类是父子关系,可以用目标类的引用接收代理对象.

模拟cglib在内存中生成的代理对象:

原对象:

public class Customer {
    public String order(String foodName) {
        return foodName;
    }

    public void test() {

    }
}

代理对象:

public class AgentCustomer extends Customer {
    MethodInterceptor methodInterceptor;
    public AgentCustomer(MethodInterceptor methodInterceptor) {
        this.methodInterceptor = methodInterceptor;
    }
    @Override
    public String order(String foodName) {
        try {
            Method method = Customer.class.getMethod("order", String.class);
            Object result = methodInterceptor.intercept(this, method, new Object[]{foodName}, null);
            return (String) result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return super.order(foodName);
    }

    @Override
    public void test() {
        try {
            Method method = Customer.class.getMethod("order", String.class);
            methodInterceptor.intercept(this, method, new Object[]{}, null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        super.test();
    }
}

测试:

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Customer customer = new Customer();
        //创建MethodInterceptor对象,里面的实现就是我们配置的增强方法
        MethodInterceptor interceptor = new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws
                    Throwable {
                if ("order".equals(method.getName())) {
                    System.out.println("模拟方法前增强方法");
                    Object result = method.invoke(customer, args);
                    System.out.println("模拟方法后增强方法");
                    return result + "增强后";
                } else {
                    return method.invoke(customer, args);
                }
            }
        };
        AgentCustomer agentCustomer = new AgentCustomer(interceptor);
        String order = agentCustomer.order("红烧肉");
        System.out.println(order);
    }
}

打印结果:

模拟方法前增强方法
模拟方法后增强方法
红烧肉增强后
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值