AOP中实现动态代理的两种方式

 一种代理方式是代理已经实现了接口的类,jdkProxy;

jdkProxy是Java类库中自带的类;创建代理对象的方式: 

实现代理需要基于Proxy类和InvocationHandler接口,使用Proxy类中的newProxyInstance()方法来完成创建,同时在该方法中直接创建实现InvocationHandler接口的匿名内部类对象,并实现invoke方法在该方法中进行方法的增强。

 final IProduce producer=new Produce();
        /*注意这里通过Proxy类中的静态方法newProxyInstance来创建对象,注意其中需要创建接口InvocationHandler的匿名对象来进行方法增强*/
    IProduce jdkProduce=(IProduce) Proxy.newProxyInstance(producer.getClass().getClassLoader(),producer.getClass().getInterfaces(), new InvocationHandler(){

        @Override
        /*在这里进行所需要的方法增强实现*/
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            Object ret=null;
            Float money=(Float)args[0];
            
            if("Service".equals(method.getName())){
                args[0]=money*1.6f;
                
                 ret=method.invoke(producer,args);//money+money*0.6f);
            }
            if("AfterService".equals(method.getName())){
             //注意这个1.5默认是double类型的,所以需要在尾端加上f,标注出来
            args[0]=money*1.5f;
            //注意这里映射到对象的方法中,并带入参数
            ret=method.invoke(producer, args);
            }
        
            
            // TODO Auto-generated method stub
            return ret;
        }
         
     });

另一种代理方式能代理未实现接口的类,但不能代理final修饰的终止类,cglib;

cglib需要从外部导入jar包才能使用;实现代理需要基于Enhancer类,并使用该类中的create方法来创建;在该方法中创建实现MethodInterceptor接口的匿名内部类对象,并在intercept方法,在该方法中编写方法增强模块。

 final Produce producer=new Produce();
    Produce cglibProduce=(Produce) Enhancer.create(producer.getClass(), producer.getClass().getInterfaces(),new MethodInterceptor() {
            
            @Override
            public Object intercept(Object arg0, Method arg1, Object[] arg2,
                    MethodProxy arg3) throws Throwable {
                
                // 在这里对具体方法实现加强
                return null;
            }
        });

归纳总结发现两种动态代理的方式其实在整体框架上非常相似,但是显然cglib创建代理的适应面更广,在Spring的AOP中,是通过cglib来创建动态代理的。

原文地址:https://www.cnblogs.com/zwwang/p/13254260.html