spring 动态代理

注意:动态代理代理的是接口

一、过程

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();
    }
}
原文地址:https://www.cnblogs.com/wt7018/p/13339188.html