码迷,mamicode.com
首页 > 其他好文 > 详细

Enhance基本例子

时间:2017-03-27 00:35:44      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:org   new   glib   out   after   super   code   test   reflect   

太晚了,有些东西没有补充,回头再补上。
先上Demo
1.要执行的方法
  1. package enhancerTest;
  2. /**
  3. * Created by LiuSuSu on 2017/3/26.
  4. */
  5. public class UserService {
  6. public void doxx(){
  7. System.out.println("do...");
  8. }
  9. }
2. 代理类
  1. package enhancerTest;
  2. import org.springframework.cglib.proxy.MethodInterceptor;
  3. import org.springframework.cglib.proxy.MethodProxy;
  4. import java.lang.reflect.Method;
  5. /**
  6. * Created by LiuSuSu on 2017/3/26.
  7. */
  8. public class CglibCallBackUserService implements MethodInterceptor {
  9. /**
  10. * cglib调用的
  11. *
  12. * @param o 调用对象
  13. * @param method 调用的方法
  14. * @param args 参数
  15. * @param methodProxy 代理的方法
  16. * @return
  17. * @throws Throwable
  18. */
  19. @Override
  20. public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
  21. System.out.println("before " + method.getName());
  22. //注意invoke代理的是自己,这是一个递归,死循环
  23. //Object obj= methodProxy.invoke(o, args);
  24. Object obj = methodProxy.invokeSuper(o, args);
  25. System.out.println("after " + method.getName());
  26. return obj;
  27. }
  28. }
3.测试方法
  1. package enhancerTest;
  2. import org.springframework.cglib.proxy.Enhancer;
  3. /**
  4. * Created by LiuSuSu on 2017/3/26.
  5. */
  6. public class EnhanceTest {
  7. public static void main(String[] args) {
  8. Enhancer enhancer = new Enhancer();
  9. enhancer.setSuperclass(UserService.class);
  10. enhancer.setCallback(new CglibCallBackUserService());
  11. UserService service = (UserService) enhancer.create();
  12. service.doxx();
  13. System.out.println("over");
  14. }
  15. }
4.运行结果
before doxx
do...
after doxx
over

灵活性上远远大于传统的代理模式。

Enhance基本例子

标签:org   new   glib   out   after   super   code   test   reflect   

原文地址:http://www.cnblogs.com/LiuChunfu/p/6624769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!