springAOP秘书老总案例

要想完成这个案例,首先了解,什么是AOP

在这里插入图片描述

在这里插入图片描述

如上图,有两个类,A类和B类。

我们可以通过AOP,实现在使用A类的methodA方法之前,先调用B类的methodb1()方法,然后再执行自己的mehodA()方法,再调用B类的methodb2()方法。

在了解了AOP的概念知道呢,我们就可以来对该案例进行分析了
在这里插入图片描述

如上图,我们想要在老总类调用eat()吃的方法时,秘书类先调用自己的daojiu()倒酒方法,然后老总类再调用自己的eat()方法,最后秘书类再调用自己的huazi()方法.

思维导图:
在这里插入图片描述

代码如下:

ILaoZong

package com.lbl.proxy;

public interface ILaoZong {
    
    
    void eat();
}

LaoZongImpl

package com.lbl.proxy;

public class LaoZongImpl implements ILaoZong {
    
    
    @Override
    public void eat() {
    
    
        System.out.println("吃三下锅");
    }
}

MiShu

package com.lbl.proxy;

public class MiShu {
    
    
    public void dianyan(){
    
    
        System.out.println("点烟");
    }
    public void daojiu(){
    
    
        System.out.println("倒酒");
    }

}

proxyTest

@Test
public void test01(){
    
    
    LaoZongImpl laoZong = new LaoZongImpl();
    MiShu miShu = new MiShu();
    ClassLoader classLoader=LaoZongImpl.class.getClassLoader();
    Class[] interfaces = {
    
    ILaoZong.class};
    InvocationHandler handler=new InvocationHandler() {
    
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
            miShu.daojiu();
            Object returnVal = method.invoke(laoZong, args);
            miShu.dianyan();
            return returnVal;
        }
    };
    ILaoZong iLaoZong = (ILaoZong) Proxy.newProxyInstance(classLoader,interfaces , handler);
    iLaoZong.eat();
}

运行结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37924905/article/details/108981095