CGLib动态代理

2020-05-13  本文已影响0人  养一只tom猫

pom依赖:

<dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
</dependency>

目标类:

public class UserService {

    public String delete(){
        System.out.println("删除用户..........");
        return "cglib  hello";
    }

}

方法拦截器:


public class SimpleProxy implements MethodInterceptor {

    private SimpleProxy(){}

    private static volatile SimpleProxy simpleProxy;

    public static SimpleProxy getInstance(){
        if (simpleProxy == null){
            synchronized (SimpleProxy.class){
                if (simpleProxy == null){
                    simpleProxy = new SimpleProxy();
                }
            }
        }
        return simpleProxy;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("后置");
        return result;
    }

}

测试类:

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);

        enhancer.setCallback(SimpleProxy.getInstance());
        UserService userService = (UserService) enhancer.create();
        String result = userService.delete();
        System.out.println("返回值  = "+result);
    }

测试结果:


image.png

CGLib的动态代理不同于JDK动态代理,众所周知JDK的动态代理需要实现接口,CGLib的动态代理可以不实现接口 .

不同于JDK的是CGLib动态代理底层最终不是使用反射调用方法 , 而是通过大量switch case 得到方法的index , 最终通过index直接调用相应方法.

上一篇下一篇

猜你喜欢

热点阅读