请使用CGLib编写一个动态代理的实际应用案例代码。
参考回答
问题:请使用CGLib编写一个动态代理的实际应用案例代码。
以下是使用CGLib实现动态代理的实际应用案例。我们将通过CGLib为目标类的业务方法添加日志功能。通过代理类,我们可以在方法执行前后添加自定义的行为。
详细讲解与拓展
1. 目标类
首先,定义一个Service类,它包含一个执行具体业务逻辑的方法performAction。
public class Service {
public void performAction(String action) {
System.out.println("Executing action: " + action);
}
}
2. 定义方法拦截器
接着,实现CGLib的MethodInterceptor接口,定义代理逻辑。在intercept()方法中,我们添加方法执行前后的日志打印。
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
public class ServiceInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable {
// 执行方法前的自定义逻辑
System.out.println("Before method execution...");
// 调用目标类的方法
Object result = proxy.invokeSuper(obj, args);
// 执行方法后的自定义逻辑
System.out.println("After method execution...");
return result;
}
}
3. 创建代理对象
通过Enhancer类来创建代理对象。Enhancer将目标类与方法拦截器关联起来,并生成目标类的代理子类。
import org.springframework.cglib.proxy.Enhancer;
public class CGLibProxyTest {
public static void main(String[] args) {
// 创建CGLib增强器
Enhancer enhancer = new Enhancer();
// 设置目标类
enhancer.setSuperclass(Service.class);
// 设置拦截器(即方法增强逻辑)
enhancer.setCallback(new ServiceInterceptor());
// 创建代理对象
Service proxy = (Service) enhancer.create();
// 调用代理对象的方法
proxy.performAction("Sample Action");
}
}
4. 输出结果
Before method execution...
Executing action: Sample Action
After method execution...
代码解析
- 目标类:
Service类实现了一个简单的performAction方法,表示需要进行的实际操作。 - 方法拦截器:
ServiceInterceptor类实现了MethodInterceptor接口,重写了intercept()方法。在方法执行前打印日志,在执行后也打印日志。 - 增强器:在
CGLibProxyTest类中,我们使用Enhancer类来创建代理对象。Enhancer.setSuperclass()方法指定了目标类,setCallback()方法设置了拦截器。调用enhancer.create()后,生成的proxy对象是Service类的代理实例。
总结
通过以上步骤,我们使用CGLib为目标类Service创建了一个动态代理。在每次调用proxy.performAction()时,代理对象会先执行方法前的自定义逻辑,然后调用目标类的方法,最后执行方法后的自定义逻辑。CGLib通过继承目标类并重写方法来实现代理,适用于没有接口的类,或者需要代理final类的方法。