CGLib动态代理

实体类

package com.mvc.rest;

public class CGLibTarget {

 public void run(){
  System.out.println("跑步");
 }
 
 public void speak(){
  System.out.println("说英语");
 }
 
}

代理类

package com.mvc.rest;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public abstract class CGLibTargetProxy implements MethodInterceptor{

 private Object target;
 
 public Object createInstance(Object object){
  this.target = object;
  Enhancer enhancer = new Enhancer();
  enhancer.setSuperclass(this.target.getClass());
  enhancer.setCallback(this);
  enhancer.setClassLoader(this.target.getClass().getClassLoader());
  return enhancer.create();
 }
 
 @Override
 public Object intercept(Object proxy, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {
  Object result = null;
  doBefore();
  result = methodProxy.invokeSuper(proxy, args);
  doAfter();
  return result;
 }

 protected abstract void doBefore();
 
 protected abstract void doAfter();
 
 
}
增强类

package com.mvc.rest;

public class CGLibTargetProxyAdvise extends CGLibTargetProxy{

 @Override
 protected void doBefore() {
  System.out.println("start");
 }

 @Override
 protected void doAfter() {
  System.out.println("end");
 }

 
}

 

测试类

package com.mvc.rest;

public class CGLibTargetTest {

 public static void main(String args[]){
  CGLibTarget target = new CGLibTarget();
  CGLibTargetProxyAdvise proxy = new CGLibTargetProxyAdvise();
  CGLibTarget obj = (CGLibTarget)proxy.createInstance(target);
  obj.speak();
  obj.run();
  
  CGLibTargetProxyAdvise2 proxy2 = new CGLibTargetProxyAdvise2();
  CGLibTarget obj2 = (CGLibTarget)proxy2.createInstance(target);
  obj2.speak();
  obj2.run();
 }
 
}

 欢迎加入我的QQ交流群425783133

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值