cglib
cglib【Code Generation Library:代码生成库】是强大高性能的代码生成包、广泛应用于许多aop框架,为其提供方法的拦截,比如说spring,可以在运行期间通过cglib继承要被动态代理的类,重写父类的方法,在子类中采用方法拦截技术拦截父类方法,并加入相应的业务逻辑代码,实现aop切面编程。
在jvm中执行程序不一定非要写java代码,只要能生成字节码,jvm并不关心字节码来源,平时写java代码是编译器生成的jvm字节码,而cglib底层是通过asm字节码技术实现动态代理
ASM
位于字节码之上、直接操作字节码的框架,
ASM是一个java字节码操控框架,可以以二进制的形式修改已有类,ASM可以直接生成二进制class文件,也可以在类被加载如java虚拟机之前改变类的行为,asm从类文件中读入信息,甚至可以根据用户要求生成新类
ASM在创建class字节码的过程中,操纵的是底层jvm汇编指令级别,需要对class组织了解。
字节码技术
字节码(bytecode)是一种包含执行程序、由一序列 op 代码/数据对 组成的二进制文件。字节码是一种中间码,它比机器码更抽象,需要直译器转译后才能成为机器码的中间代码
借助字节码能做什么
字节码作用于运行期,一般用来运行期改变类的行为,可以结合代理模式
使用ASM框架提供了ClassWriter 接口,通过访问者模式进行动态创建class字节码,看下面的例子:
public class Test {
public static void main(String[] args) throws IOException {
//ClassReader用于读取原有字节码,ClassWriter用于写入字节码,
ClassWriter cs = new ClassWriter(0);
//通过vist确定类的同步信息 java版本号 类修饰符 类的权限定名
cs.visit(Opcodes.V1_8,Opcodes.ACC_PUBLIC,"Duck",null, "java/lang/Object",null);
//构造函数
MethodVisitor mv = cs.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// 定义code方法
MethodVisitor methodVisitor = cs.visitMethod(Opcodes.ACC_PUBLIC, "code", "()V", null, null);
methodVisitor.visitCode();
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
methodVisitor.visitLdcInsn("I'm a Duck,Just Coding.....");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
methodVisitor.visitInsn(Opcodes.RETURN);
methodVisitor.visitMaxs(2, 2);
methodVisitor.visitEnd();
cs.visitEnd();
// 使classWriter类已经完成
// 将classWriter转换成字节数组写到文件里面去
byte[] data = cs.toByteArray();
File file = new File("D://Duck.class");
FileOutputStream fout = new FileOutputStream(file);
fout.write(data);
fout.close();
}
}
生成Duck.class
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
public class Duck {
public Duck() {
}
public void code() {
System.out.println("I'm a Duck,Just Coding.....");
}
}
cglib测试代码
1.代理的目标类Dao
public class Dao {
public void select() {
System.out.println("select 1 from dual");
}
public void insert() {
System.out.println("insert into ...");
}
public final void delete() {
System.out.println("delete from ...");
}
}
2.代理类DaoProxy、DaoAnotherProxy
public class DaoProxy implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("begin intercept");
//invokeSuper方法调用目标类的方法
proxy.invokeSuper(obj, args);
System.out.println("end intercept");
return obj;
}
}
public class DaoAnotherProxy implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("开始intercept");
proxy.invokeSuper(obj, args);
System.out.println("结束intercept");
return obj;
}
}
3.过滤器DaoFilter
/**
* 返回数值表示顺序
*/
public class DaoFilter implements CallbackFilter {
@Override
public int accept(Method method) {
if("select".equalsIgnoreCase(method.getName())) {
return 0;
} else if ("delete".equalsIgnoreCase(method.getName())) {
return 1;
}
return 2;
}
}
测试类Client
public class Client {
public static void main(String[] args) {
//将代理类存到本地磁盘
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "C:\\Users\\LJW\\IdeaProjects\\design\\structure\\src\\main\\java\\cglib\\classes");
//实例化增强器
Enhancer enhancer = new Enhancer();
//设置需要代理的目标类
enhancer.setSuperclass(Dao.class);
//设置拦截对象 回调的实现类
// enhancer.setCallback(new DaoProxy());
enhancer.setCallbacks(new Callback[]{new DaoProxy(), new DaoAnotherProxy(),NoOp.INSTANCE});
enhancer.setCallbackFilter(new DaoFilter());
//使用create 返回Object 生成代理类并返回实例
Dao dao = (Dao) enhancer.create();
//select优先级高 使用DaoProxy
dao.select();
//无法代理被final修饰的方法
dao.delete();
dao.insert();
}
}
输出
begin intercept
select 1 from dual
end intercept
delete from ...
insert into ...
代理类
以上仅有select方法得到加强【原因看后面分析】,并将一系列代理类通过System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY存放在磁盘中,观察生成的类
这里用idea反编译后得到的,生成三个类,都是以Dao开头命名一个EnhancerBy还有一个FastClass相关
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// 可以看到代理类继承代理类重写了select方法,可以当做为入口方法,这里没有delete()的原因是final修饰,无法重写,也没有insert() 【过滤器返回索引为2,而索引为2的代理类为空,用NoOp.INSTANCE表示】
//
package cglib.mapper;
import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import net.sf.cglib.proxy.NoOp;
public class Dao$$EnhancerByCGLIB$$7ddef0e2 extends Dao implements Factory {
private boolean CGLIB$BOUND;
public static Object CGLIB$FACTORY_DATA;
private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
private static final Callback[] CGLIB$STATIC_CALLBACKS;
private MethodInterceptor CGLIB$CALLBACK_0;
private MethodInterceptor CGLIB$CALLBACK_1;
private NoOp CGLIB$CALLBACK_2;
private static Object CGLIB$CALLBACK_FILTER;
private static final Method CGLIB$select$1$Method;
private static final MethodProxy CGLIB$select$1$Proxy;
private static final Object[] CGLIB$emptyArgs;
static void CGLIB$STATICHOOK1() {
CGLIB$THREAD_CALLBACKS = new ThreadLocal();
CGLIB$emptyArgs = new Object[0];
Class var0 = Class.forName("cglib.mapper.Dao$$EnhancerByCGLIB$$7ddef0e2");
Class var1;
CGLIB$select$1$Method = ReflectUtils.findMethods(new String[]{"select", "()V"}, (var1 = Class.forName("cglib.mapper.Dao")).getDeclaredMethods())[0];
CGLIB$select$1$Proxy = MethodProxy.create(var1, var0, "()V", "select", "CGLIB$select$1");
}
final void CGLIB$select$1() {
super.select();
}
public final void select() {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (this.CGLIB$CALLBACK_0 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
//如果不为null 说明有相应代理类实现MethodInterceptor 会调用该对象的intercept加强方法
if (var10000 != null) {
var10000.intercept(this, CGLIB$select$1$Method, CGLIB$emptyArgs, CGLIB$select$1$Proxy);
} else {
super.select();
}
}
public static MethodProxy CGLIB$findMethodProxy(Signature var0) {
String var10000 = var0.toString();
switch(var10000.hashCode()) {
case -1716030215:
if (var10000.equals("select()V")) {
return CGLIB$select$1$Proxy;
}
}
return null;
}
public Dao$$EnhancerByCGLIB$$7ddef0e2() {
CGLIB$BIND_CALLBACKS(this);
}
public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] var0) {
CGLIB$THREAD_CALLBACKS.set(var0);
}
public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] var0) {
CGLIB$STATIC_CALLBACKS = var0;
}
private static final void CGLIB$BIND_CALLBACKS(Object var0) {
Dao$$EnhancerByCGLIB$$7ddef0e2 var1 = (Dao$$EnhancerByCGLIB$$7ddef0e2)var0;
if (!var1.CGLIB$BOUND) {
var1.CGLIB$BOUND = true;
Object var10000 = CGLIB$THREAD_CALLBACKS.get();
if (var10000 == null) {
var10000 = CGLIB$STATIC_CALLBACKS;
if (CGLIB$STATIC_CALLBACKS == null) {
return;
}
}
Callback[] var10001 = (Callback[])var10000;
var1.CGLIB$CALLBACK_2 = (NoOp)((Callback[])var10000)[2];
var1.CGLIB$CALLBACK_1 = (MethodInterceptor)var10001[1];
var1.CGLIB$CALLBACK_0 = (MethodInterceptor)var10001[0];
}
}
public Object newInstance(Callback[] var1) {
CGLIB$SET_THREAD_CALLBACKS(var1);
Dao$$EnhancerByCGLIB$$7ddef0e2 var10000 = new Dao$$EnhancerByCGLIB$$7ddef0e2();
CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
return var10000;
}
public Object newInstance(Callback var1) {
throw new IllegalStateException("More than one callback object required");
}
public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
CGLIB$SET_THREAD_CALLBACKS(var3);
Dao$$EnhancerByCGLIB$$7ddef0e2 var10000 = new Dao$$EnhancerByCGLIB$$7ddef0e2;
switch(var1.length) {
case 0:
var10000.<init>();
CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
return var10000;
default:
throw new IllegalArgumentException("Constructor not found");
}
}
public Callback getCallback(int var1) {
CGLIB$BIND_CALLBACKS(this);
Object var10000;
switch(var1) {
case 0:
var10000 = this.CGLIB$CALLBACK_0;
break;
case 1:
var10000 = this.CGLIB$CALLBACK_1;
break;
case 2:
var10000 = this.CGLIB$CALLBACK_2;
break;
default:
var10000 = null;
}
return (Callback)var10000;
}
public void setCallback(int var1, Callback var2) {
switch(var1) {
case 0:
this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
break;
case 1:
this.CGLIB$CALLBACK_1 = (MethodInterceptor)var2;
break;
case 2:
this.CGLIB$CALLBACK_2 = (NoOp)var2;
}
}
public Callback[] getCallbacks() {
CGLIB$BIND_CALLBACKS(this);
return new Callback[]{this.CGLIB$CALLBACK_0, this.CGLIB$CALLBACK_1, this.CGLIB$CALLBACK_2};
}
public void setCallbacks(Callback[] var1) {
this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
this.CGLIB$CALLBACK_1 = (MethodInterceptor)var1[1];
this.CGLIB$CALLBACK_2 = (NoOp)var1[2];
}
static {
CGLIB$STATICHOOK1();
}
}
代理大致过程
1.生成的代理类Dao$$EnhancerByCGLIB$$7ddef0e2继承了要代理的Dao类并实现Factory【这里的Factory应该是cglib的工厂接口,不做关心】
2.代理类会为委托方法【以Dao类的select为例】生成两个方法,以final修饰,一个重写select
public final void select()
{
MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
if (tmp4_1 == null)
{
tmp4_1;
CGLIB$BIND_CALLBACKS(this);
}
if (this.CGLIB$CALLBACK_0 != null)
return;
super.select();
}
另外一个CGLIB$select$1 默认调用父类的select()方法
final void CGLIB$select$1()
{
super.select();
}
当执行代理对象的select时,会先判断是否存在实现MethodInterceptor接口的CGLIB$CALLBACK_0,如果存在则调用intercept方法
fastclass机制
cglib执行代理方法效率快的原因:采用fastclass机制
简单来说就是:为代理类和被代理类各生产一个class,该class会为代理类或被代理类分配一个index(int),该index当做为一个入参,fastclass可以直接定位到要调用的方法直接进行调用,省去反射调用【反射效率较低】,即对一个类的方法建立索引,通过索引直接调用相应方法。
cglib和jdk动态代理的区别
1.jdk动态代理实现了被代理对象的接口,cglib是继承了被代理的对象【通过字节码技术创建这个类的子类,实现动态代理】
2.都是在运行期间,jdk是直接写class字节码,cglib使用asm框架写字节码,实现更复杂
3.java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法时用InvokeHandler,cglib是通过继承要被代理类的机制
jdk动态代理要求
1.动态代理类实现InvocationHandler接口【必须】
2.被代理的类必须要实现一个接口
3.使用Proxy.newProxyInstance产生代理对象
cglib要求
1.jdk动态代理类库中已有,而cglib必须加入第三方依赖(cglib、asm)
5.jdk调用代理方法,通过反射机制,cglib通过fastclass机制直接调用方法,这方面cglib执行效率更高。
速率上的区别
对于创建实例:jdk更快,相比之下cglib创建实例的过程比较繁琐
对于方法执行效率:cglib更快,基于asm操作字节码技术和fastclass机制(通过索引调用方法),比基于反射的jdk动态代理来的快。
据说高版本的jdk有了很大的提升,还没实践过,具体参考
https://blog.csdn.net/xlgen157387/article/details/82497594
cglib的局限性(缺点)
1.cglib无法代理final修饰的类和final修饰的方法
原因:
final类不能被继承、没有子类、final类中修饰的方法默认是final
final方法不能被子类的方法覆盖
而cglib的底层的代理类恰好就是通过继承要代理的目标类来实现种种操作。
cglib代理内部类
内部类Target
public class Target {
class Student {
public String name = "garwer";
}
}
测试类Client
//测试代码
public class Client {
public static void main(String[] args) throws ClassNotFoundException {
Class inner = Class.forName("cglib.constructionTest.Target$Student");
//获取内部类构造函数
Constructor[] constructors = inner.getDeclaredConstructors();
for(Constructor c : constructors) {
System.out.println(Arrays.toString(c.getParameterTypes()));////输出[class cglib.constructionTest.Target] 证明形参是外部类
}
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(Target.Student.class);
enhancer.setCallback(NoOp.INSTANCE);
Target.Student student = (Target.Student) enhancer.create();
System.out.println(student.name);
}
}
输出结果:
[class cglib.constructionTest.Target]
Exception in thread "main" java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given...
原因:
代理目标对象不能是内部类【内部类的创建依赖外部类】,如果是内部类,cglib代理内部会获取到一个有参构造函数【参数是外部类对象】
如果非要代理内部类,有两种方式
1.内部类加static【即static class Student,因为被static修饰的内部类可以直接作为一个普通类来使用,而不需实例一个外部类】
2.改为Target.Student student = (Target.Student) enhancer.create(new Class[]{Target.class}, new Object[]{new Target()}); 在cglib创建类对象时传入外部类对象
Spring代理选择
当bean实现接口时,spring使用jdk动态代理
当bean没实现接口,spring使用cglib
可以通过配置强制走cglib,<aop:aspectj-autoproxy proxy-target-class="true"/>,如果是基于注解的方式,比如说springboot项目的启动类,可以使用@EnableAspectJAutoProxy(proxyTargetClass=true)注解来强制使用cglib
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
/**
* Determine whether the supplied {@link AdvisedSupport} has only the
* {@link org.springframework.aop.SpringProxy} interface specified
* (or no proxy interfaces specified at all).
*/
private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
Class<?>[] ifcs = config.getProxiedInterfaces();
return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
}
}
网友评论