1.pom.xml(当然也可以引入spring的jar包)
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency>2.目标对象类(不再依赖接口)
public class ForumServiceImpl { public void removeTopic(int topicId){ System.out.println("模拟删除Topic记录:"+topicId); try {Thread.currentThread().sleep(20);} catch (InterruptedException e) {e.printStackTrace();} } public void removeForum(int forumId){ System.out.println("模拟删除Forum记录:"+forumId); try {Thread.currentThread().sleep(40);} catch (InterruptedException e) {e.printStackTrace();} } }3.提供返回带有横切逻辑的最终代理实例方法
public class CglibProxy implements MethodInterceptor { private Enhancer enhancer=new Enhancer(); /** * 动态创建带有横切逻辑的代理实例 * @param enhancer 增强对象 * @param method * @param args * @param methodProxy 拦截目标对象类的所有方法的子类 * @return * @throws Throwable */ @Override public Object intercept(Object enhancer, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { PerformanceMonitor.begin(enhancer.getClass().getName() + method.getName()); Object obj = methodProxy.invokeSuper(enhancer,args);//通过代理子类调用父类的方法 PerformanceMonitor.end(); return obj; } public Object getProxy(Class clazz){ enhancer.setSuperclass(clazz);//目标对象类 enhancer.setCallback(this); return enhancer.create();//通过字节码技术创建目标对象类的子类实例作为代理 } }至于PerformanceMonitor与MethodPerformance,请参考前文.
public class TestForumService { public static void testCglib() { ForumServiceImpl proxy= (ForumServiceImpl) new CglibProxy().getProxy(ForumServiceImpl.class); proxy.removeForum(10); proxy.removeTopic(1012); } public static void main(String[] args) { testCglib(); } }