Java学习--spring框架--入门AOP

本文介绍了Java中的AOP(面向切面编程)概念,包括切面、通知、目标、代理和连接点等核心概念,并详细阐述了如何使用动态代理来实现AOP,通过设置接口及其实现类,以及创建动态代理类来演示具体操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AOP

AOP:面向切面编程。
切面(Aspect):横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象。
通知(Advice):切面必须完成的工作。
目标(Target):被通知的对象。
代理(Peoxy):向目标对象应用通知之后创建的对象。
连接点(Joinpoint):程序执行的某个特定位置。
切点(pointcut):每个类都拥有多个连接点。

使用动态代理来实现

使用一个动态代理类来处理,在对指定的类外层加上动态代理对象,对其进行处理。
设置接口ArithmeticCalculator.java

public interface ArithmeticCalculator {
    int add(int i,int j);
    int sub(int i ,int j);
    int mul(int i ,int j);
    int div(int i ,int j);

}

设置接口的实现类ArithmeticCalculatorImpl.java

public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
    public int add(int i, int j) {
        return i+j;
    }

    public int sub(int i, int j) {
        return i-j;
    }

    public int mul(int i, int j) {
        return i*j;
    }

    public int div(int i, int j) {
        return i/j;
    }
}

动态代理类ArithmeticCalculatorLoggingProxy.java

public class ArithmeticCalculatorLoggingProxy {
//    要代理的对象
    private ArithmeticCalculator calculator;

    public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator calculator){
        this.calculator = calculator;
    }
    public ArithmeticCalculator getLoggingProxy(){
        ArithmeticCalculator proxy = null;
//        代理对象由哪一个类加载器加载
        ClassLoader loader = calculator.getClass().getClassLoader();
//        代理对象的类型,即其中有哪些方法
        Class[] interfacees = new Class[]{ArithmeticCalculator.class};
//        当调用代理对象其中的方法时,执行该代码
        InvocationHandler handler = new InvocationHandler() {
            /**
             * proxy:正在返回的那个代理对象,一般情况下,在invoke方法中都不使用该对象。
             * method:正在被调用的方法
             * args:调用方法时,传入的参数
             */
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
//                执行方法前的操作
                System.out.println("ATGUIGU --> The method "+methodName+" begins with "+ Arrays.asList(args));
//                执行方法
                Object result = method.invoke(calculator,args);
//                执行方法后的操作
                System.out.println("ATGUIGU --> The method "+methodName+" ends with "+ result);
                return result;
            }
        };

        proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader,interfacees ,handler);
        return proxy;
    }
}

主函数

public static void main(String[] args) {
        ArithmeticCalculator calculator = new ArithmeticCalculatorImpl();
        ArithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(calculator).getLoggingProxy();

        int result = proxy.add(1,2);
        System.out.println("--> "+result);
    }

运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值