使用JDK动态代理实现日志的打印

1.创建bean

        创建接口

package com.spring.aop.beans;

public interface Calculator {
    int add(int a,int b);
    int sub(int a,int b);
    int mul(int a,int b);
    int div(int a,int b);
}

        实现接口

package com.spring.aop.beans;

import org.springframework.stereotype.Repository;

@Repository(value = "calculator")
public class CalculatorImpl implements Calculator {
    @Override
    public int add(int a, int b) {
        int result = a + b;
        return result;
    }

    @Override
    public int sub(int a, int b) {
        int result = a - b;
        return result;
    }

    @Override
    public int mul(int a, int b) {
        int result = a * b;
        return result;
    }

    @Override
    public int div(int a, int b) {
        int result = a / b;
        return result;
    }
}

  2.创建java类

package com.spring.log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class LoggingProxy {
    //被代理的对象
    private  Object target;

    public LoggingProxy(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        //获取被代理对象的类加载器
        ClassLoader classLoader =target.getClass().getClassLoader();
        //获取被代理对象实现的接口
        Class<?>[] interfaces = target.getClass().getInterfaces();
       Object proxy= Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            /*
            参数说明
            invoke方法中就是要执行的扩展的功能
            该方法中参数的说明:
            proxy:传入的代理对象
            method:要调用的方法
            args:调用方法时传入的参数
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //获取方法名
                String methodName =method.getName();
                System.out.println("Logging: The method "+methodName+"begins with"+ Arrays.toString(args));
                //执行方法,即方法的调用转到被代理对象上
                Object result=method.invoke(target,args);
                System.out.println("Logging: The method "+methodName+"returns"+ result);
                return result;
            }
        });
        return proxy;
    }
}

3.测试

/*
   测试动态代理
*/
@Test
public void testProxy(){
    Calculator cal = new CalculatorImpl();
    //获取代理对象
    Calculator calculator = (Calculator) new LoggingProxy(cal).getProxy();
    //调用加减乘除的方法
    calculator.add(10,2);
    calculator.sub(10,2);
    calculator.mul(10,2);
    calculator.div(10,2);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_43555873

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值