The realization mechanism of "sping revelation" 12 and SPRINGAOP

Source: Internet
Author: User
Tags stub throwable

The implementation mechanism of SPRINGAOP

Design mode proxy mode

Refer to my previous proxy mode

Http://www.cnblogs.com/cutter-point/p/5226642.html

Here's a simple case.

 Package Spring.aop.designPattern; /** *  * Title:ISubject.java * Description: Proxy mode resource  interface class @author@version  1.0  */Publicinterface  isubject        {public void request ();}

 PackageSpring.aop.designPattern;/*** * * Title:SubjectImpl.java * Description: accessed by the visitor, or access to the resource implementation class *@authorxiaof * @date April 7, 2018 *@version1.0 **/ Public classSubjectimplImplementsIsubject {@Override Public voidrequest () {//TODO auto-generated Method StubSystem.out.println ("This is Subjectimpl cutter_point!")); }}

 PackageSpring.aop.designPattern;/*** * Title:SubjectProxy.java * Description: Proxy Implementation class *@authorxiaof * @date April 7, 2018 *@version1.0 **/ Public classSubjectproxyImplementsIsubject {PrivateIsubject subject; @Override Public voidrequest () {System.out.println ("Pre Operation Subjectproxy"); if(Subject! =NULL) subject.request (); System.out.println ("After Operation Subjectproxy"); }     Publicisubject Getsubject () {returnsubject; }     Public voidSetsubject (isubject subject) { This. Subject =subject; }    }
 Package Spring.aop.designPattern; Import org.junit.Test;  Public class Main {    @Test    publicvoid  test1 () {        new  Subjectimpl ();         New subjectproxy ();        Sp.setsubject (SI);                Sp.request ();    }}

Test a wave:

This is, for example, when we are going to proxy for Subjectimpl, we need to implement a proxy class object based on the Isubject interface.

Well, based on this point,

Disadvantage 1: If we do not have a class interface type, and is a third-party class object, such as we now have a subjectimpl2, this class does not implement the Isubject interface, then our Subjectimpl can also do proxy? It's obviously not possible.

Disadvantage 2: We find that a Subjectimpl object agent is to implement a proxy class Subjectproxy, if we have a project with a water object need to proxy, then we need to create 10,000 proxy class, OK, I will be crazy anyway ...

Dynamic Agent

The dynamic proxy for this JDK is primarily the proxy class and the Invocationhandler interface

 Package Spring.aop.designPattern; /** *  * Title:ISubject.java * Description: Proxy mode resource  interface class @author@version  1.0  */Publicinterface  isubject        {public void request ();}
 PackageSpring.aop.designPattern;/*** * * Title:SubjectImpl.java * Description: accessed by the visitor, or access to the resource implementation class *@authorxiaof * @date April 7, 2018 *@version1.0 **/ Public classSubjectimplImplementsIsubject {@Override Public voidrequest () {//TODO auto-generated Method StubSystem.out.println ("This is Subjectimpl cutter_point!")); }}

proxy class

 PackageSpring.aop.dynamicPorxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;Importjava.util.Date;ImportSpring.aop.util.DateUtil;/*** * Title:RequestCtrlInvocationHandler.java * DESCRIPTION:JDK Dynamic proxy Object *@authorxiaof * @date April 7, 2018 *@version1.0 **/ Public classRequestctrlinvocationhandlerImplementsInvocationhandler {/*** Proxy Object*/    PrivateObject Target; /*** 00:00:00*/    PrivateString BeginTime; /*** 00:00:00*/    PrivateString EndTime;  PublicRequestctrlinvocationhandler (Object target, String beginTime, String endTime) { This. target =Target;  This. BeginTime =BeginTime;  This. EndTime =EndTime; } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//determine if it is the request method, and if it is an interception operation        if(Method.getname (). Equals ("Request"))) {            //determine whether the current time is within the range, and if so, then do the corresponding operation            if(Dateutil.isindate (NewDate (), BeginTime, EndTime)) {System.out.println ("Time in interval, interception success"); returnMethod.invoke (target, args); } Else{System.err.println ("Out-of-band Time"); return NULL; }        }        returnMethod.invoke (target, args); }}

Final Test:

Current time!

Then we modify the time interval to see if there will be a different result!!!

0-12 pips

So let's change the time to 22.

Interception success

Not many BB, this is still a problem, unable to handle interface class problems

Dynamic byte-code generation

Using Cblib

 PackageSpring.aop.cglib;ImportJava.lang.reflect.Method;Importjava.util.Date;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;ImportOrg.springframework.cglib.proxy.MethodInterceptor;ImportOrg.springframework.cglib.proxy.MethodProxy;ImportSpring.aop.util.DateUtil;/*** * Title:RequestCtrlCallback.java * Description: Dynamic Bytecode technology *@authorxiaof * @date April 7, 2018 *@version1.0 **/ Public classRequestctrlcallbackImplementsMethodinterceptor {Private Static FinalLog logger = Logfactory.getlog (requestctrlcallback.class); /*** 00:00:00*/    PrivateString BeginTime; /*** 00:00:00*/    PrivateString EndTime;  Publicrequestctrlcallback (String beginTime, String endTime) { This. BeginTime =BeginTime;  This. EndTime =EndTime; } @Override PublicObject Intercept (Object arg0, Method arg1, object[] arg2, Methodproxy arg3)throwsThrowable {//if we need to intercept the method, then do the appropriate action        if(Arg1.getname (). Equals ("Request"))) {            if(Dateutil.isindate (NewDate (), BeginTime, EndTime)) {                //within the corresponding time interval, the successfulLogger.info ("Successfully intercept the corresponding interval, release!") "); returnArg3.invokesuper (arg0, arg2); } Else{logger.error ("Error time interval!! "); return NULL; }        }                returnArg3.invokesuper (arg0, arg2); }     PublicString Getbegintime () {returnBeginTime; }     Public voidsetbegintime (String beginTime) { This. BeginTime =BeginTime; }     PublicString Getendtime () {returnEndTime; }     Public voidsetendtime (String endTime) { This. EndTime =EndTime; }}
 PackageSpring.aop.cglib;Importorg.junit.Test;ImportOrg.springframework.cglib.proxy.Enhancer;ImportSpring.aop.designPattern.SubjectImpl; Public classMain {@Test Public voidtest1 () {//using the Cglib proxy objectString beginTime = "00:00:00"; String EndTime= "20:00:00"; Enhancer Enhancer=Newenhancer (); //set proxy class objectEnhancer.setsuperclass (Subjectimpl.class); Enhancer.setcallback (NewRequestctrlcallback (BeginTime, endTime)); //Build Proxy ObjectSubjectimpl proxyobj =(Subjectimpl) enhancer.create ();    Proxyobj.request (); }}

Results show:

The realization mechanism of "sping revelation" 12 and SPRINGAOP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.