一、概念

通过代理对象访问目标对象,增强目标对象的方法

二、常规例子

JDK动态代理(接口)

interface HelloInterface{

    void helloWorld();
}
class HelloImpl implements HelloInterface{

    @Override
    void helloWorld()
    {
        System.out.println("helloWorld!");
    }

}

class HelloProxy implements helloInterface{
    HelloImpl hello;
    HelloProxy(HelloImpl hello){
    this.hello=hello;
    }
    @Override
    void proxyHelloWorld()
    {
        System.out.println("方法前增强!");
        hello.helloWorld();
        System.out.println("方法后增强!");
    }

}

public class test{
    public static void main(String[] args) {
        HelloImpl hello=new HelloImpl();
        HelloProxy proxy=new HelloProxy(hello);
        proxy.helloWorld();
    }

}
//结果
//方法前增强!
//helloWorld!
//方法后增强!

CGLIB动态代理(子类)

class Hello{
    void helloWorld()
    {
        System.out.println("helloWorld!");
    }
}
class HelloProxy extends Hello{
    HelloImpl hello;
    HelloProxy(HelloImpl hello){
    this.hello=hello;
    }
    void helloWorld()
    { 
        System.out.println("方法前增强!");
        hello.helloWorld();
        System.out.println("方法后增强!");
    }

}

public class test{
    public static void main(String[] args) {
        HelloImpl hello=new HelloImpl();
        HelloProxy proxy=new HelloProxy(hello);
        proxy.helloWorld();
    }

}
//结果
//方法前增强!
//helloWorld!
//方法后增强!
三、在SpringAOP中的应用

1、JDK动态代理

基于接口(Java只能单继承,想要目标类与代理类产生联系,只能实现统一接口)

目标对象需要实现接口,代理对象不需要实现接口(看Java源码及反编译知,动态在内存中生成的真实代理类实现了目标接口)

2、CGLIB动态代理

动态在内存中生成目标类的子类来实现代理

03-27 03:35