1
2 1------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------
2
何为动态代理,就不扯皮了,上一篇博客刚刚提到,那cglib动态代理又怎么写,我拿个和上个例子相似的案例来写
具体案例:
一个SomeServiceImpl接口
1
2
3
4
5
6
7
8
9
10
11
12 1package cn.dawn.day10cglibdtproxy;
2
3
4/**
5 * Created by Dawn on 2018/3/8.
6 */
7public class SomeServiceImpl {
8 public void doSome() {
9 System.out.println("do something");
10 }
11}
12
一个测试类,我直接在测试类中使用cglib动态代理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 1package cn.dawn.day10cglibdtproxy;
2
3
4import org.springframework.cglib.proxy.Enhancer;
5import org.springframework.cglib.proxy.MethodInterceptor;
6import org.springframework.cglib.proxy.MethodProxy;
7
8import java.lang.reflect.Method;
9
10/**
11 * Created by Dawn on 2018/3/8.
12 */
13public class Test {
14 public static void main(String[] args) {
15 //模板
16 final SomeServiceImpl service=new SomeServiceImpl();
17 //cglib动态代理
18 Enhancer enhancer=new Enhancer();
19 //设置模板
20 enhancer.setSuperclass(service.getClass());
21 //回调函数
22 enhancer.setCallback(new MethodInterceptor() {
23 public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
24 System.out.println("前置增强内容---------------");
25 methodProxy.invoke(service,objects);
26 return null;
27 }
28 });
29 //创建代理对象
30 SomeServiceImpl proxy = (SomeServiceImpl)enhancer.create();
31 //代理对象调用原方法
32 proxy.doSome();
33
34 }
35}
36
他的写法就如上所示,需要以上的注释所标明的步骤
值得一提的是MethodProxy这个东西,他见过吗?他类似Method都是对此类的方法的反射,但是前者是Spring在高版本后出现的,他的写法优良,更具性能