SpringAOP之动态代理

1、AOP概念

AOP: Aspect Oriented Program 面向切面编程。是oop思想的延续。
思想:横向抽取,减少重复代码,提高开发效率
目的:AOP使用动态代理目的的是对象增强

常见情况:编码过滤、事务处理

2、AOP原理(动态代理模式)

代理模式:为指定对象提供一个代理对象,达到控制对指定对象的访问(代理对象起中介作用)
方式一:jdk提供的动态代理(jdk提供的代理模式)
方式二:cglib动态代理(Spring提供的代理模式) 

3、代理模式

  3.1、jdk提供的动态代理模式

要求:被代理对象必须实现接口才能产生代理对象
特点:Proxy.newProxyInstance();为指定的对象生成代理对象  
public class ProxyByJDK {
    //被代理对象一定要实现的接口(此处要写的是被代理对象。)
    private CustomerServiceImpl customerServiceImpl;
    public ProxyByJDK(CustomerServiceImpl customerServiceImpl) {
        super();
        this.customerServiceImpl = customerServiceImpl;
    }
    public  CustomerService  getCustomerServiceByProxy() {
        CustomerService customerService = (CustomerService)Proxy.newProxyInstance(CustomerServiceImpl.class.getClassLoader(), 
                 CustomerServiceImpl.class.getInterfaces(),new InvocationHandler() {        
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("开启事务");//t=  session.beginTransaction();
                //反射调用方法
                Object object=null;
                try {
                    object=  method.invoke(customerServiceImpl, args);
                    //执行业务方法结束提交事务
                    System.out.println("提交事务");//t.commit();
                }catch (Exception e) {
                    // TODO: handle exception
                    //t.rollback();
                }
                return object;
            }
        });
        return customerService;    
    }
} 

3.2、cglib提供的动态代理模式

要求:被代理对象的类不能用final修饰,对代理对象进行继承生产代理对象
特点:要生成代理对象的帮助类           
             //1.生成代理对象(cglib)
                    public  CustomerService getCustomerServiceByCglibProxy() {
                    //1.设置要生成代理对象的帮助类
                    Enhancer en=new Enhancer();
                    //2.配置(2.1 要配置的类是谁)
                    en.setSuperclass(class1);
                    //3.生成代理对象,给回调接口(主要是使用方法拦截的接口,目的是给方法增强)
                    en.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object paramObject, Method method, Object[] paramArrayOfObject, MethodProxy methodProxy) throws Throwable {
                        // TODO Auto-generated method stub
                        System.out.println("开启事务");
            //paramObject对象上的methodProxy方法执行,执行需要传入参数paramArrayOfObject
            Object  object = methodProxy.invokeSuper(paramObject, paramArrayOfObject);
                    System.out.println("提交事务");
                    return object;
                    }
                });
             CustomerService customerService = (CustomerService)en.create();
            return customerService;
}
原文地址:https://www.cnblogs.com/a77355699/p/8034843.html