使用CGLIB实现动态代理

CGLIB 是一个强大的、高性能的代码生成库。其被广泛应用于 AOP 框架(Spring、dynaopaop)中,用以提供方法拦截操作

依赖导入

方法一: jar包方式

需要下载jar包,下载地址:
https://repo1.maven.org/maven2/cglib/cglib/3.3.0/cglib-3.3.0.jar
https://repo1.maven.org/maven2/org/ow2/asm/asm/7.0/asm-7.0.jar

方法二: maven

<!-- cglib 动态代理依赖 begin --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.5</version></dependency><!-- cglib 动态代理依赖 stop -->

实现

委托类

public class UserService {  
	public void save() {  
	System.out.println("保存数据");  
	}  
}

代理类

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 UserServiceCglibProxy implements MethodInterceptor {
    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        // 设置回调方法
        enhancer.setCallback(this);
        // 创建代理对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable {

        System.out.println("开启事务");
        Object result = proxy.invokeSuper(object, args);
        System.out.println("提交事务");
        return result;
    }

    public static void main(String[] args) {
        UserServiceCglibProxy userServiceCglibProxy = new UserServiceCglibProxy();
        UserService userServiceCglibProxyInstance = (UserService) userServiceCglibProxy.getInstance(new UserService());
        userServiceCglibProxyInstance.save();
    }
}