当前位置: 移动技术网 > IT编程>开发语言>Java > 从mybatis源码看JDK动态代理

从mybatis源码看JDK动态代理

2020年04月06日  | 移动技术网IT编程  | 我要评论

网上好多说到动态代理的文章内容都是这样子的:

一个实际干事的类real;一个被创造的代理类proxy。

proxy调用real中被代理的方法;有模有样的在被代理的方法前后打印出一些字符串。

比如下面的例子:

 1 public class jdkproxy {
 2     static interface iproxy{
 3         string say(string s);
 4     }
 5     static class real implements iproxy{
 6         @override
 7         public string say(string s) {
 8             system.out.println("说完了,返回结果");
 9             return s;
10         }
11     }   
12 
13     static class myinvocationhandler implements  invocationhandler{
14         private object real;
15 
16         public myinvocationhandler(object real) {
17             this.real = real;
18         }
19 
20         @override
21         public object invoke(object proxy, method method, object[] args) throws throwable {
22             object res=null;
23             if(method.getname().equals("say")){
24                 system.out.println("say start...");
25                 res=method.invoke(real,args);
26                 system.out.println("say end...");
27             }
28             return res;
29         }
30     }    
31 
32     public static void main(string[] args) {
33         execu1();      
34     }
35 
36     private static void execu1(){
37         system.getproperties().put("sun.misc.proxygenerator.savegeneratedfiles","true");
38         real real=new real();
39         iproxy proxy=(iproxy) proxy.newproxyinstance(real.getclass().getclassloader(), real.getclass().getinterfaces(),new myinvocationhandler(real));
40         string s=proxy.say("abc");
41         system.out.println(s);
42     }   
43 
44 }

上面21-27行代码是调用被代理的方法;

如果我现在不调用被代理的方法,而是直接写一个方法体。

代码如下:

 1 public class jdkproxy {
 2     static interface iproxy{
 3         string say(string s);
 4     }
 5     static class real implements iproxy{
 6         @override
 7         public string say(string s) {
 8             system.out.println("说完了,返回结果");
 9             return s;
10         }
11     }   
12 
13     static class myinvocationhandler implements  invocationhandler{
14         private object real;
15 
16         public myinvocationhandler(object real) {
17             this.real = real;
18         }
19 
20         @override
21         public object invoke(object proxy, method method, object[] args) throws throwable {
22            return "我什么也不代理,我直接就是一个方法";
23         }
24     }    
25 
26     public static void main(string[] args) {
27         execu1();      
28     }
29 
30     private static void execu1(){
31         system.getproperties().put("sun.misc.proxygenerator.savegeneratedfiles","true");
32         real real=new real();
33         iproxy proxy=(iproxy) proxy.newproxyinstance(iproxy.class.getclassloader(),new class[]{iproxy.class},new myinvocationhandler(real));
34         string s=proxy.say("abc");
35         system.out.println(s);
36     }   
37 
38 }

改动代码是22行的代码。

如果不需要被代理的方法了,那么还需要实际干活的类吗?

继续修改代码:

 1 public class jdkproxy {
 2     static interface iproxy{
 3         string say(string s);
 4     }   
 5 
 6     static class myinvocationhandler implements  invocationhandler{
 7         
 8 
 9         @override
10         public object invoke(object proxy, method method, object[] args) throws throwable {
11            return "我什么也不代理,我直接就是一个方法";
12         }
13     }    
14 
15     public static void main(string[] args) {
16         execu1();      
17     }
18 
19     private static void execu1(){
20         system.getproperties().put("sun.misc.proxygenerator.savegeneratedfiles","true");      
21         iproxy proxy=(iproxy) proxy.newproxyinstance(iproxy.class.getclassloader(),new class[]{iproxy.class},new myinvocationhandler());
22         string s=proxy.say("abc");
23         system.out.println(s);
24     } 
25 }

 上面的程序依然能够正常运行。

从这个层面来说,动态代理就是给我们创造了一个类,至于有没有实际干活的类无关。

网上到处都在说mybatis接口编程的用的是动态代理,创造代理类我们很好理解,那么他到底代理了什么类呢?

先来个简单的mybatis例子:

1 sqlsessionfactory sqlsessionfactory=new sqlsessionfactorybuilder().build(resources.getresourceasstream("mybatis-config.xml"));
2 sqlsession sqlsession= sqlsessionfactory.opensession();
3 irolemapper irolemapper=sqlsession.getmapper(irolemapper.class);
4 list<role> list=irolemapper.getrole(1l);

第三行代码就应该是获取代理的过程;irolemapper指向具体的代理类。

下面查看源码:

getmapper()源码:

 1  public <t> t getmapper(class<t> type, sqlsession sqlsession) {
 2     final mapperproxyfactory<t> mapperproxyfactory = (mapperproxyfactory<t>) knownmappers.get(type);
 3     if (mapperproxyfactory == null) {
 4       throw new bindingexception("type " + type + " is not known to the mapperregistry.");
 5     }
 6     try {
 7       return mapperproxyfactory.newinstance(sqlsession);
 8     } catch (exception e) {
 9       throw new bindingexception("error getting mapper instance. cause: " + e, e);
10     }
11   }

代码比较简洁,代理类是在第7行生成的。进入newinstance()方法:

newinstance()源码:

1 protected t newinstance(mapperproxy<t> mapperproxy) {
2     return (t) proxy.newproxyinstance(mapperinterface.getclassloader(), new class[] { mapperinterface }, mapperproxy);
3   }
4 
5   public t newinstance(sqlsession sqlsession) {
6     final mapperproxy<t> mapperproxy = new mapperproxy<>(sqlsession, mapperinterface, methodcache);
7     return newinstance(mapperproxy);
8   }

第1行的newinstance调用的是jdk的代理方法

第5行的newinstance是mybatis自己的方法,根据jdk动态代理的调用规则,第6行的mapperproxy一定继承了invocationhandler接口,并且实现了接口方法invoke();

invoke()源码

 1  public object invoke(object proxy, method method, object[] args) throws throwable {
 2     try {
 3       if (object.class.equals(method.getdeclaringclass())) {
 4         return method.invoke(this, args);
 5       } else if (method.isdefault()) {
 6         if (privatelookupinmethod == null) {
 7           return invokedefaultmethodjava8(proxy, method, args);
 8         } else {
 9           return invokedefaultmethodjava9(proxy, method, args);
10         }
11       }
12     } catch (throwable t) {
13       throw exceptionutil.unwrapthrowable(t);
14     }
15     final mappermethod mappermethod = cachedmappermethod(method);
16     return mappermethod.execute(sqlsession, args);
17   }

invoke()方法体中并没有调用    res=method.invoke(real,args);这类的代码。说明一个问题,这里并没有我们常说的real这样的类。

总结:

1.jdk动态代理只是需要一个接口,体的干活类不是必须的;至于具体做什么,由程序员在invoke()中去实现。

2.mybatis用了jdk动态代理,但是并没有提供被代理的类;只是提供了一个代理类或者干脆说提供了一个我们看不见的类用于执行sql

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网