码迷,mamicode.com
首页 > 编程语言 > 详细

spring 系列6 动态代理

时间:2020-03-30 23:38:54      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:基本   pre   实现   cep   obj   nts   param   imp   接口   

在业务中使用动态代理,一般是为了给需要实现的方法添加预处理或者添加后续操作,但是不干预实现类的正常业务,把一些基本业务和主要的业务逻辑分离。
基于JDK的动态代理只需知道两个东西:1.InvocationHandler(接口)、2.Proxy(类)

一、创建一个接口

public interface Subject{
    void hello(String param);
}

二、实现接口

public class SubjectImpl implements Subject{
    public void hello(String param){
        System.out.println("Hello " + param);
    }
}

三、创建代理类

public class SubjectProxy implements InvocationHandler{
    private Subject subject;
    public SubjectProxy(Subject subject){
        this.subject = subject;
    }
    
    public Object invoke(Object proxy, Method method, Object[] args) throws Exception{
        System.out.println("begin");
        Object invoke = method.invoke(subject, args);
        System.out.println("end");
        return invoke;
    }
}

四、测试

public class Main {
    public static void main(String[] args) {
        Subject subject = new SubjectImpl();
        InvocationHandler subjectProxy = new SubjectProxy(subject);
        Subject proxyInstance = (Subject) Proxy.newProxyInstance(subjectProxy.getClass().getClassLoader(), subject.getClass().getInterfaces(), subjectProxy);
        proxyInstance.hello("123");
    }
}

在被代理之后,实际调用的方法是SubjectProxy的invoke方法,这样可以在不修改业务类的情况下对业务类增加一些日志等操作。

spring 系列6 动态代理

标签:基本   pre   实现   cep   obj   nts   param   imp   接口   

原文地址:https://www.cnblogs.com/mantishell/p/12601788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!