CGLib是采用字节码方式注入到程序中的,这种方式就像C++中的Detour库注入汇编代码,从而达到监控函数运行的效果。由于CGLib是采用继承的关系,故它不能代理final类。以下是测试代码。
CglibProxy.java
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibProxy implements MethodInterceptor {
// private static CglibProxy proxy = new CglibProxy();
private Enhancer enhancer = new Enhancer();
public Object getProxy(Class clazz) {
enhancer.setSuperclass(clazz);// 设置需要创建子类的类
enhancer.setCallback(this);
return enhancer.create();// 通过字节码技术动态创建子类实例
}
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
Object result = arg3.invokeSuper(arg0, arg2);
return result;
}
}
public class UserServiceImpl{
public void removeUser(int userId) {
System.out.println("模拟删除用户:" + userId);
}
public void addUser(int userId) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
CglibProxy proxy = new CglibProxy();
UserServiceImpl userService =(UserServiceImpl)proxy.getProxy(UserServiceImpl.class);
userService.removeUser(7);
}
}