jdk的动态代理

jdk的动态代理也是mybatis的主要实现原理:

即动态生成dao层接口的实现类对象

代理的原理:不改变原对象的核心功能来做增强扩展

这里动态代理的实现条件:

1.原对象
2.公共接口
3.代理工厂
4.jdk工具接口

InvocationHandler

1.原对象:

package org.example.dynamic;

public class StudentService implements IStudentService {

    @Override
    public void add(){
       // System.out.println(new Date() + "进入");
        System.out.println("add student to db");
        // System.out.println(new Date() + "退出");
    }

    @Override
    public void find(){
        System.out.println("find student from db");
    }
}

2.公共接口:

package org.example.dynamic;

public interface IStudentService {
    void add();

    void find();
}

3.代理工厂

import java.util.Date;


@Data
public class LogInvocationHandler implements InvocationHandler {

    private Object target;

    // 增强时候执行的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String typeName = target.getClass().getName();
        String methodName = method.getName();

        // 增强
        System.out.println(new Date() + " 进入 " + typeName+"."+methodName);
        // 让原对象干
        Object invoke = method.invoke(target, args);

        System.out.println(new Date() + " 退出 " + typeName+"."+methodName);
        return invoke;
    }
}

测试类:

package org.example.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class Test01 {
        // TARGET
        IStudentService studentService = new StudentService();
        LogInvocationHandler logHandler1 = new LogInvocationHandler();
        logHandler1.setTarget(studentService);
        // proxy
        IStudentService studentServiceProxy = (IStudentService) Proxy.newProxyInstance(studentService.getClass().getClassLoader(),
                new Class[]{IStudentService.class}, logHandler1);

        studentService.add();
        studentServiceProxy.find();

    }
}

测试结果:

add student to db
Thu Aug 29 20:43:55 CST 2024 进入 org.example.dynamic.StudentService.find
find student from db
Thu Aug 29 20:43:55 CST 2024 退出 org.example.dynamic.StudentService.find
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值