CGLIB模式

CGLIB是没有实现接口的类,完成代理。

package com.spring.chapterEleven; 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 CglibCustomerLoginAction implements MethodInterceptor{ private Enhancer enhancer = new Enhancer(); //建立被代理类的子类,并返回这个子类 public Object CreateProxyInstance(Class clz) { enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); } //在被代理类的方法执行前后增加新功能 public Object intercept (Object obj, Method method, Object[] methodParameters, MethodProxy methodProxy) throws Throwable { if(method.getName().contains("execute")){ System.out.println("begin the login validate"); Object theobj = methodProxy.invokeSuper(obj, methodParameters); System.out.println("end the login validate"); return theobj; }else{ Object theobj = methodProxy.invokeSuper(obj, methodParameters); return theobj; } } }

测试

public static void main(String[] args) { CglibCustomerLoginAction cglibCustomerLoginAction = new CglibCustomerLoginAction(); CustomerLoginAction pAction = (CustomerLoginAction)cglibCustomerLoginAction. CreateProxyInstance(CustomerLoginAction.class); pAction.execute(); }

你可能感兴趣的:(CGLIB模式)