CGLib之Enhancer
Enhancer允许为非接口类型创建一个Java代理。Enhancer动态创建了给定类型的子类但是拦截了所有的方法。和Proxy不一样的是,不管是接口还是类他都能正常工作。
来个场景模拟一下AOP
- package cglib.enhancer;
- public class Hello {
- public String sayHello(boolean throwException) throws Exception {
- System.out.println("hello everyone!");
- if(throwException)
- throw new Exception("test exception");
- return "123";
- }
- }
ProxyFactory用于创建增强代理实现了方法拦截
- package cglib.enhancer;
- 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 ProxyFactory implements MethodInterceptor {
- //要代理的原始对象
- private Object obj;
- public Object createProxy(Object target) {
- this.obj = target;
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(this.obj.getClass());// 设置代理目标
- enhancer.setCallback(this);// 设置回调
- enhancer.setClassLoader(target.getClass().getClassLoader());
- return enhancer.create();
- }
- @Override
- public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
- Object result = null;
- try {
- // 前置通知
- before();
- result = proxy.invokeSuper(obj, args);
- // 后置通知
- after();
- } catch (Exception e) {
- exception();
- }finally{
- beforeReturning();
- }
- return result;
- }
- private void before() {
- System.out.println("before method invoke");
- }
- private void after() {
- System.out.println("after method invoke");
- }
- private void exception() {
- System.out.println("method invoke exception");
- }
- private void beforeReturning() {
- System.out.println("before returning");
- }
- }
- package cglib.enhancer;
- public class EnhancerTest {
- public static void main(String[] args) throws Exception {
- Hello hello = new Hello();
- ProxyFactory cglibProxy = new ProxyFactory();
- Hello proxy = (Hello) cglibProxy.createProxy(hello);
- String result=proxy.sayHello(true);
- System.out.println(result);
- }
- }
运行结果:
- before method invoke
- hello everyone!
- method invoke exception
- before returning
- null
- before method invoke
- hello everyone!
- after method invoke
- before returning
- 123
接下来我们了解下Enhancer可以使用的Callback接口。
- package net.sf.cglib.proxy;
- /**
- * All callback interfaces used by {@link Enhancer} extend this interface.
- * @see MethodInterceptor
- * @see NoOp
- * @see LazyLoader
- * @see Dispatcher
- * @see InvocationHandler
- * @see FixedValue
- */
- public interface Callback
- {
- }
接口都很简单。
先来一个基础POJO类:
- public class SampleClass {
- public String test(String input) {
- return "Hello world!";
- }
- }
FixedValue
使用FixedValue可以很容易的替换掉方法的返回值。
- @Test
- public void testFixedValue() throws Exception {
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(SampleClass.class);
- enhancer.setCallback(new FixedValue() {
- @Override
- public Object loadObject() throws Exception {
- return "Hello cglib!";
- }
- });
- SampleClass proxy = (SampleClass) enhancer.create();
- assertEquals("Hello cglib!", proxy.test(null));
- }
SampleClass的子类实例,当所有的方法被调用的时候返回匿名FixedValue回调返回的值。当然了如果方法返回的不是String类型例如,hashcode()将抛出一个类型转换异常,因为"Hello cglib!"不能转换为java.lang.Number类型。
InvocationHandler
- @Test
- public void testInvocationHandler() throws Exception {
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(SampleClass.class);
- enhancer.setCallback(new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
- return "Hello cglib!";
- } else {
- throw new RuntimeException("Do not know what to do.");
- }
- }
- });
- SampleClass proxy = (SampleClass) enhancer.create();
- assertEquals("Hello cglib!", proxy.test(null));
- assertNotEquals("Hello cglib!", proxy.toString());
- }
MethodInterceptor
- @Test
- public void testMethodInterceptor() throws Exception {
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(SampleClass.class);
- enhancer.setCallback(new MethodInterceptor() {
- @Override
- public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
- throws Throwable {
- if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
- return "Hello cglib!";
- } else {
- return proxy.invokeSuper(obj, args);
- }
- }
- });
- SampleClass proxy = (SampleClass) enhancer.create();
- assertEquals("Hello cglib!", proxy.test(null));
- assertNotEquals("Hello cglib!", proxy.toString());
- proxy.hashCode(); // Does not throw an exception or result in an endless loop.
- }
唯一需要注意的就是proxy.invokeSuper和proxy.invoke的区别。invokeSuper是退出当前interceptor的处理,进入下一个callback处理,invoke则会继续回调该方法,如果传递给invoke的obj参数出错容易造成递归调用。
LazyLoader
尽管LazyLoader唯一的方法和FixedValue的一模一样,但是他们还是有一个根本上的区别。相比于Dispatcher,lazyLoader在第一次获取了loadObject后,会进行缓存,后续的请求调用都会直接调用该缓存的属性。
这个是有道理的,如果你的对象是昂贵的在其创建,不知道对象什么时候被使用。请注意,一些增强的类的构造函数必须被代理对象和延迟加载的对象。因此,确保还有另一个廉价的(可能保护)构造函数获得或使用一个接口类型的代理。你可以选择提供参数的调用Enhancer#create(Object...)。
Dispatcher
Dispatcher和LazyLoader很想但是每次调用方法的时候不会存储加载的对象。这允许改变一个类的实现但不改变原来的对象。
再者说一些构造函数必须被代理和生成的对象调用。
ProxyRefDispatcher
这个类携带了代理对象的引用,通过它的签名调用。例如这允许委托方法调用代理的另一个方法。要清楚这很容易造成死循环,并且总是导致死循环如果同样的方法被ProxyRefDispatcher#loadObject(Object)调用。
NoOp
像名字所说的一样,这个类不做任何操作。相反地,它委托每个方法的调用给被增强类的方法实现。