CGLIB动态代理模式与jdk动态代理模式的区别是: 目标代理类不需要实现接口,同样也可以实现代理。
直接看一个简单的cglib应用,看他是如何实现代理的。
第一步,新建一个maven项目,并引入cglib依赖:
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
第二步,新建一个目标类,名为HelloWorld:
package com.hand.proxy.cglib;
public class HelloWorld {
public void sayHello() {
System.out.println("CGLIB动态代理模式!");
}
}
第三步,创建代理类,里面主要有2个方法,一个为获取代理的实例方法,另一个为需要重写的方法,此类需要实现MethodInterceptor接口,该接口很简单,此包含一个方法intercept:
public interface MethodInterceptor extends Callback
{
/**
* All generated proxied methods call this method instead of the original method.
* The original method may either be invoked by normal reflection using the Method object,
* or by using the MethodProxy (faster).
* @param obj "this", the enhanced object
* @param method intercepted Method
* @param args argument array; primitive types are wrapped
* @param proxy used to invoke super (non-intercepted method); may be called
* as many times as needed
* @throws Throwable any exception may be thrown; if so, super method will not be invoked
* @return any value compatible with the signature of the proxied method. Method returning void will ignore this value.
* @see MethodProxy
*/
public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args,
MethodProxy proxy) throws Throwable;
}
在创建实例前,我们需要使用一个叫Enhancer的对象,此对象用来创建代理对象,设置目标类为超类后的同时需要回调当前类:
package com.hand.proxy.cglib;
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 CGLIBExampleProxy implements MethodInterceptor{
/**
* 指定cglib代理模式的代理类
*/
private Object target;
public Object bind(Object target) {
this.target=target;
Enhancer enhancer=new Enhancer();
//设置超类方法
enhancer.setSuperclass(this.target.getClass());
//设置一个回调方法,用来设置哪个类为代理类,this表示当前类为代理类
enhancer.setCallback(this);
//创建代理对象
return enhancer.create();
}
public Object intercept(Object obj,
Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println("CGLIB代理前");
Object object=proxy.invokeSuper(obj, args);
System.out.println("CGLIB代理后");
return object;
}
}
intercept方法的几个参数说明:
obj:表示目标对象
method:表示当前调度的方法,这里指的是HelloWorld类里面的sayHello()方法
args:表示执行方法的参数列表
MethodProxy: 表示执行目标方法的代理对象
验证结果:
package com.hand.proxy.cglib;
public class CGLIBTest {
public static void main(String[]args) {
//1.获取代理对象
CGLIBExampleProxy proxy=new CGLIBExampleProxy();
//2.获取代理对象
HelloWorld hello=(HelloWorld)proxy.bind(new HelloWorld());
//3.执行代理方法
hello.sayHello();
}
}
输出结果为:
CGLIB代理前
CGLIB动态代理模式!
CGLIB代理后
以上就是cglib代理模式的一个简单实现。通过与jdk动态代理模式的比较发现, cglib模式不需要目标类实现接口,即可实现代理。