AOP实现原理:2.CGLIB的使用

1.概念:CGLIB是一种字节码增强框架,在运行时,创建目标类子类,从而对目标类进行增强。
2.代码:切面类不变
2.1 创建一个目标类StudentService

public class StudentService {
    public void delete(){
        System.out.println("删除学生");
    }

    public void add(){
        System.out.println("添加学生");
    }

    public void update(){
        System.out.println("更新学生信息");
    }
}

2.2 在UserServiceFactory中增加一个createStudentService方法。

//    2.CGLIB实现代理
    public static StudentService createStudentService(){
        //1.创建目标对象target
        StudentService studentService = new StudentService();
        //2.声明切面类对象
        MyAspect aspect = new MyAspect();
        //3.创建增强对象
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(studentService.getClass());
        //设置回调(拦截)
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                aspect.before();
                System.out.println(o.getClass());
                System.out.println(methodProxy);
                System.out.println("拦截...");
               // Object obj = method.invoke(studentService, args);
                Object obj = methodProxy.invokeSuper(o,args);

                aspect.after();
                System.out.println("obj:"+obj);
                System.out.println("-----------------------");

                return obj;
            }
        });

        // 创建代理对象
        StudentService s = (StudentService) enhancer.create();
        return s;
    }

2.3 测试

    @Test
    public void Test(){
        StudentService studentService = UserServiceFactory.createStudentService();
        studentService.add();
        studentService.update();
        studentService.delete();
    }

显示结果


AOP实现原理:2.CGLIB的使用_第1张图片
image.png

你可能感兴趣的:(AOP实现原理:2.CGLIB的使用)