spring AOP理解——spring中的CGLIB实现AOP功能

来源:互联网 发布:gif剪裁软件 编辑:程序博客网 时间:2024/05/23 16:00

 

使用spring中的CGLIB实现AOP功能--代码

 

import java.lang.reflect.Method;

 

import net.sf.cglib.proxy.Enhancer;

import net.sf.cglib.proxy.MethodInterceptor;

import net.sf.cglib.proxy.MethodProxy;

 

public class CglibProxyFactory implements MethodInterceptor {

 

       private Object targetObj;

 

       /**

        * 为目标对象创建代理类

        *

        * 传入要代理类,创建此类的代理实例

        *

        * @param targetObj

        *            目标对象

        * @return 返回目标对象的代理类

        */

       public Object createProxyInstances(Object targetObj) {

              this.targetObj = targetObj;

              Enhancer en = new Enhancer();

              en.setSuperclass(this.targetObj.getClass());

              en.setCallback(this);

              return en.create();

       }

 

       @Override

       public Object intercept(Object proxy, Method method, Object[] arg2, MethodProxy arg3)throws Throwable {

              MyServiceImpl myservice = (MyServiceImpl) targetObj;

              Object result = null;

              if (myservice.getTemp() != null) {

                     result = method.invoke(targetObj, arg2);

              }

              return result;

       }

}

 

 

测试

 

       @Test

       public void testCglibProxy() {

              CglibProxyFactory proxy = new CglibProxyFactory();

              MyServiceImpl ms = (MyServiceImpl) proxy.createProxyInstances(new MyServiceImpl("xxx"));

              ms.save();

       }

原创粉丝点击