SSM之SpringAOP

Spring AOP概念

  • AOP(Aspect Oriented Programming)是面向切面编程
    就是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。简单说,就是在不改变方法源代码的基础上,对方法进行功能增强。本质上是生成了一个新的类,叫做代理类
  • AOP对程序的扩展方式采用动态代理的方式(JDK动态代理和Cglib动态代理两种方式)
    在这里插入图片描述

Spring动态代理

  • JDK的动态代理
    》Proxy类的静态方法可以创建代理对象
static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

》三个参数
参数1:ClassLoader loader类加载器,用来加载代理对象
参数2:Class<?>[] interfaces目标类的字节码对象数组。因为代理的是接口,需要知道接口中的所有方法
参数3:InvocationHandler h执行句柄,代理对象处理的核心逻辑就在该接口中

案例:老总吃饭

  • TestJdkProxy
public class TestJdkProxy {
    public static void main(String[] args){
        //Jdk代理
        LaoZong laoZong = new LaoZong();
        MiShu miShu = new MiShu();
        //创建一个代理类,创建该类的对象
        ClassLoader classLoader= LaoZong.class.getClassLoader();
        Class[] interfaces = new Class[]{ILaoZong.class};
        //处理器
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                miShu.laiBeiJiu();
                Object returnValue = method.invoke(laoZong,args);
                miShu.laiGenYan();
                return returnValue;
            }
        };
        ILaoZong iLaoZong = (ILaoZong) Proxy.newProxyInstance(classLoader,interfaces,handler);
        iLaoZong.eat();
    }
}
  • 老总类
public void eat(){
        System.out.println("eat san xia guo");
        System.out.println("eat wa wa cai");
    }

    @Override
    public void run() {
        System.out.println("ao ao pao");
    }

    @Override
    public void sleep() {
        
        System.out.println("ao ao shui");
    }
  • 秘书类
public void laiBeiJiu(){
        System.out.println("laiBeiJiu");
    }
    public void laiGenYan(){
        System.out.println("laiGenYan");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值