AOP底层实现 两种代理技术(jdb动态代理 cglib代理)

JDK代理技术

package com.wjl.c_proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
 
import com.wjl.service.UserService;
import com.wjl.service.UserServiceImpl;
public class UserServiceProxyFactory implements InvocationHandler{
    private UserService us;
    public UserServiceProxyFactory(UserService us) {
       super();
       this.us = us;
    }
    public UserService getUserServiceProxy()
    {
       //生成动态代理
       UserService usProxy=(UserService) Proxy.newProxyInstance(UserServiceProxyFactory.class.getClassLoader(),
              UserServiceImpl.class.getInterfaces(),
              this);
       //返回
       return usProxy;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] objs) throws Throwable {
       System.out.println("打开事务");
       Object invoke=method.invoke(us, objs);
       System.out.println("提交事务");
       return invoke;
    }
}

cglib代理

package com.wjl.c_proxy;
import java.lang.reflect.Method;
 
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
 
import com.wjl.service.UserService;
import com.wjl.service.UserServiceImpl;
 
//cglib代理
public class UserServiceProxyFactory2 implements MethodInterceptor  {
   
    public UserService getUserServiceProxy() {
       Enhancer en=new Enhancer();//帮我们生成代理对象
       en.setSuperclass(UserServiceImpl.class);//设置对谁代理
       en.setCallback(this);//代理要做什么
       UserService us=(UserService) en.create();//创建代理对象
       return us;
    }
 
    @Override
    public Object intercept(Object proxyobj, Method method, Object[] arg, MethodProxy methodProxy) throws Throwable {
       //打开事务
       System.out.println("打开事务");
       //调用原有方法
       Object returnValue=methodProxy.invokeSuper(proxyobj, arg);
       //提交事务
       System.out.println("提交事务");
       return returnValue;
    }
}

测试

package com.wjl.c_proxy;
 
import org.junit.Test;
 
import com.wjl.service.UserService;
import com.wjl.service.UserServiceImpl;
 
public class Demo {
    //JDK动态代理
    @Test
    public void fun1()
    {
       UserService us=new UserServiceImpl();
       UserServiceProxyFactory factory=new UserServiceProxyFactory(us);
       UserService usProxy = factory.getUserServiceProxy();
       usProxy.save();
       //代理对象与被代理对象实现了相同的接口
       //代理对象与被代理对象没有继承关系
       System.out.println(usProxy instanceof UserServiceImpl);//false
    }
    //cglib代理
    @Test
    public void fun2()
    {
       UserServiceProxyFactory2 factory = new UserServiceProxyFactory2();
       UserService usProxy = factory.getUserServiceProxy();
       usProxy.save();
       //判断代理对象是否属于被代理对象类型
       System.out.println(usProxy instanceof UserServiceImpl);//true
    }
}

 

 

上一篇:Dubbo学习系列之九(Shiro+JWT权限管理)


下一篇:依赖注入在 dotnet core 中实现与使用:1 基本概念