首页 > 编程语言 > 详细

spring 动态代理

时间:2020-07-19 14:26:13      阅读:55      评论:0      收藏:0      [点我收藏+]

一、过程

1、接口类

2、普通类继承接口

3、ProxyInvocationHandler.java(固定格式)

4、应用类

二、案例

public interface User {
    void add();
    void delete();
    void update();
    void query();
}
public class UserImpl implements User {
    public void add() {
        System.out.println("增加一条数据");
    }

    public void delete() {
        System.out.println("删除一条数据");
    }

    public void update() {
        System.out.println("更新一条数据");
    }

    public void query() {
        System.out.println("查询一条数据");
    }
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyInvocationHandler implements InvocationHandler {

    // 被代理的接口
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }
    // 生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(
                this.getClass().getClassLoader(), target.getClass().getInterfaces(), this
        );
    }
    // 处理代理实例, 并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 添加方法
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String msg){
        System.out.println("[debug]:" + msg);
    }
}
public class client {
    public static void main(String[] args) {
        // 真实角色
        UserImpl userImpl = new UserImpl();
        // 代理角色,不存在
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        // 设置要代理的对象
        pih.setTarget(userImpl);
        // 接口类
        User user = (User) pih.getProxy();
        user.add();
    }
}

 

spring 动态代理

原文:https://www.cnblogs.com/wt7018/p/13339188.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!