Spring Technology Insider: The implementation principle of Spring AOP (I.)

Source: Internet
Author: User
Tags aop constructor inheritance reflection regular expression serialization static class throwable

I. Overview of SPRINGAOP
1. AOP Concept
AOP is the abbreviation for aspect-oriented programming (plane-oriented programming). Wikipedia explains the following:
Aspect is a new modular mechanism for describing crosscutting concerns (crosscutting concern) scattered across objects, classes, or functions. The separation of the crosscutting concerns from the point of concern is the core of the program design oriented to the aspect. Separation of concerns enables code that solves a particular domain problem to be independent of the business logic code, where the code of the business logic no longer contains calls to specific code for the picking problem, and the relationship between business logic and a particular domain problem is encapsulated and maintained by facets, so that changes that are scattered throughout the application can be managed well.
2, advice notice
The advice definition provides a weaving interface for aspect enhancement at the connection point. In spring AOP, he mainly describes the tangent behavior that spring AOP injects around method invocations. Advice is the interface defined in Org.aopalliance.aop.Advice. This unified interface is used in spring AOP, and this interface provides additional details and extensions for AOP aspect-enhanced weaving capabilities, such as providing a more specific type of notification, such as Beforeadvice,afteradvice,throwsadvice.
2.1 Beforeadvice
First we start with the Beforeadvice:
In the inheritance relationship of Beforeadvice, the pre-enhanced interface Methodbeforeadvice for the target method to be enhanced is defined, and a callback function is implemented using this predecessor interface:

void before (Method method,object[] args,object target) throws Throwable;

As a callback function, the implementation of the Before method is called back when the target method is invoked after it is configured in advice to the target method. The specific parameters are: Method object, which is the reflection object of the target method; An array of object[] objects containing the input parameters of the target method. Taking Countingbeforeadvice as an example to illustrate the specific use of Beforeadvice, Countbeforeadvice is the implementation of the interface Methodbeforeadvice, he just counted the number of times the method was called, as a facet enhancement implementation , he will make statistics based on the method name of the calling method, and put the statistical results into a map based on the method name and the number of calls as key-value pairs. The code is as follows:

public class Countingbeforeadvice extends Methodcounter implements Methodbeforeadvice {//Implementation method pre-notification Methodbeforeadvice interface method public void before (method M, object[] args, Object target) throws Throwable {//with the target object method as a parameter, call the parent class Methodcounter
    The Count method counts the number of method calls count (m); }} countingbeforeadvice the source of the parent class Methodcounter is as follows: public class Methodcounter implements Serializable {//Method name---M of method call
    AP collection, number of calls to the storage method private hashmap<string, integer> map = new hashmap<string, integer> ();
    Total number of calls to all methods private int allcount;
    Count method calls, Countingbeforeadvice call entry protected void count (method m) {count (M.getname ()); }//Statistics the number of calls to the specified name method protected void count (String methodName) {//Gets the number of calls to the specified name method from the collection of method names, such as the method call Inte
Ger i = Map.get (methodName); If the number of calls is not NULL, the number of calls is added to 1, and if the number of calls is NULL, the number of calls is set to 1 i = (i = null)?
        New Integer (I.intvalue () + 1): New integer (1);
        Reset the number of method calls saved in the collection map.put (MethodName, i); TheMethod total number of calls plus 1 ++allcount;
        }//Gets the number of calls to the specified name method public int Getcalls (String methodName) {Integer i = map.get (methodName);
    return (i! = null? I.intvalue (): 0);
    }//Gets the total number of calls for all methods public int getcalls () {return allcount; 
    } public Boolean equals (Object) {return (other! = null && other.getclass () = = This.getclass ());
    } public int hashcode () {return getclass (). Hashcode (); }
}

2.2 Afteradvice
In the advice implementation system, Spring also provides afteradvice this type of notification, here the implementation of Afterreturningadvice notification as an example, the code is as follows:

Public interface Afterreturningadvice extends Afteradvice
The callback method of the {////post-notification, called after the target method object call finishes and returns successfully
The returnvalue parameter is the return value of the target method object, which is the target method object, and
    the input parameter of the args//Target method object is
    void Afterreturning (Object returnvalue, method, object[] args, Object target) throws Throwable;
}

The Afterreturning method is also a callback function, the AOP application needs to provide the aspect enhancement in this interface implementation the concrete design, after this advice notification is configured correctly, when the target method call ends and returns successfully, the interface is called by SPRINGAOP. As in the previous analysis, in the Spring AOP package, you can see the Countingafterreturningadvice, which is basically the same:

public class Countingafterreturningadvice extends Methodcounter implements Afterreturningadvice {
    // callback method for implementing post-notification Afterreturningadvice public
    void Afterreturning (Object o, Method m, object[] args, Object target) throws T hrowable {
        //calls the Count method of the parent class Methodcounter, the number of calls to the statistic method
        count (m);}
}

In the interface method afterreturning that implements Afterreturningadvice, you can call the Count method of Methodcounter to complete the count of the number of target method calls based on the method name.
2.3 Throwsadvice
Let's take a look at another type of advice notification Throwsadvice. For Throwsadvice, there is no interface method that needs to be implemented, he is called back when throwing an exception, and this callback is done using the reflection mechanism of AOP. You can use Countingthrowsadvice to understand how throwsadvice is used:

public static class Countingthrowsadvice extends Methodcounter implements Throwsadvice {
        //callback method when throwing an IO type exception Count the number of times the exception was called Public
        void Afterthrowing (IOException ex) throws Throwable {
            count (IOException.class.getName ());
        }
        //When throwing a callback method with an Uncheckedexception type exception, count the number of times the exception was called Public
        void Afterthrowing (Uncheckedexception ex) throws Throwable {
            count (UncheckedException.class.getName ());
        }
    }

3. Pointcut Tangent Point
Determines which connection point the advice notification should act on, that is, by pointcut to define a collection of methods that need to be enhanced, the selection of these collections can be done in accordance with certain rules. Pointcut often means identifying methods, for example, where these need to be enhanced can be identified by a regular expression, or matched according to a method name. The source code is as follows:

Public interface Pointcut {
    //Get class filter
    Classfilter getclassfilter ();
    Get the method of matching pointcut    
    methodmatcher getmethodmatcher ();
    The total matching standard pointcut instance
    Pointcut TRUE = truepointcut.instance;

Looking at the inheritance system of Pointcut pointcuts, it is found that the implementation classes of Pointcut pointcuts are very many, such as annotationmatchingpointcut for annotation configuration, jdkregexpmethodpointcut for regular expressions, etc. We take jdkregexpmethodpointcut as an example to analyze the specific implementation of pointcut matching, the source code is as follows:

public class Jdkregexpmethodpointcut extends Abstractregexpmethodpointcut {//Regular expression pattern to be compiled private pattern[] Compil
    Edpatterns = new Pattern[0];
    The regular expression pattern to be excluded at compile time private pattern[] Compiledexclusionpatterns = new Pattern[0]; Initializes the given pattern string array to the compiled regular expression pattern protected void initpatternrepresentation (string[] patterns) throws
    patternsyntaxexception {this.compiledpatterns = Compilepatterns (patterns); }//Initializes the given pattern string array to the regular expression pattern to be excluded at compile time protected void initexcludedpatternrepresentation (string[] excludedpatterns) thro
    WS patternsyntaxexception {this.compiledexclusionpatterns = Compilepatterns (excludedpatterns); }//Use regular expression to match the given name protected Boolean matches (String pattern, int patternindex) {Matcher Matcher = this.co
        Mpiledpatterns[patternindex].matcher (pattern);
    return matcher.matches (); }//Use the regular expression you want to exclude to match the given name protected Boolean matchesexclusion (String candidate, int patternindex) {Matcher ma Tcher = This. Compiledexclusionpatterns[patternindex].matcher (candidate);
    return matcher.matches ();
        }//Compile the given string array into a regular expression mode private pattern[] Compilepatterns (string[] source) throws Patternsyntaxexception {
        pattern[] Destination = new Pattern[source.length];
        for (int i = 0; i < source.length; i++) {Destination[i] = Pattern.compile (Source[i]);
    } return destination; }
}

4, the advisor Notifier
completes the Aspect Enhancement design (Advice) and the Focus design (Pointcut) of the target method, and requires an object to combine them, which is the advisor that accomplishes this. Through he can define which notification should be used and at which point of interest to use it. There are two properties in defaultpointcutadvisor, namely advice and pointcut. These two properties allow you to configure advice and pointcut, respectively. The source code is as follows:

public class Defaultpointcutadvisor extends Abstractgenericpointcutadvisor implements
    Serializable {//default pointcut//pointcut.true is defined in the Pointcut as: Pointcut TRUE = truepointcut.instance;
    Private Pointcut Pointcut = pointcut.true; Without a parameter construct method, create an empty notifier public defaultpointcutadvisor () {}//create a notifier that matches all methods public Defaultpointcutadvisor (ADVI
    Ce advice) {This (pointcut.true, advice); }//Create a notifier that specifies pointcuts and notifications public Defaultpointcutadvisor (Pointcut Pointcut, Advice Advice) {this.pointcut = Poi
        Ntcut;
    Setadvice (advice); }//Set pointcut for notification public void Setpointcut (Pointcut Pointcut) {this.pointcut = (Pointcut! = null? pointcut:p Ointcut.
    TRUE);
    }//Get Pointcut public Pointcut getpointcut () {return this.pointcut; The public String toString () {return getclass (). GetName () + ": pointcut [" + getpointcut () + "];
    Advice ["+ getadvice () +"] "; }
}

In the above source, the default pointcut for the notifier is pointcut.true,pointcut.true in the pointcut is defined as: Pointcut TRUE = truepointcut.instance
The instance of Truepointcut is a single piece, such as using the static class variable to hold a single instance, using the private proprietary constructor to ensure that a single piece is not created and instantiated again except in the current single implementation. The implementation of
Truepointcut and Truemethodmatcher is as follows:

/** * Canonical Pointcut instance that always matches.  * * @author Rod Johnson */@SuppressWarnings ("Serial") class Truepointcut implements Pointcut, Serializable {public

    Static final Truepointcut INSTANCE = new Truepointcut ();
     /** * Enforce Singleton pattern. * Here is the implementation of the single-piece mode, set the private constructor, so that it cannot be directly instantiated * and set a static class variable to ensure that the instance is unique */private Truepointcut () {} public Class
    Filter Getclassfilter () {return classfilter.true;
    } public Methodmatcher Getmethodmatcher () {return methodmatcher.true; }/** * Required to support serialization.
     Replaces with canonical * instance on deserialization, protecting Singleton pattern.
     * Alternative to overriding {@code equals ()}.
    */Private Object readresolve () {return INSTANCE;
    } @Override Public String toString () {return "pointcut.true"; }
}
/** * Canonical Methodmatcher instance that matches all methods.
    * * @author Rod Johnson */@SuppressWarnings ("Serial") class Truemethodmatcher implements Methodmatcher, Serializable {
    public static final Truemethodmatcher INSTANCE = new Truemethodmatcher ();
     /** * Enforce Singleton pattern.
    */Private Truemethodmatcher () {} public boolean isruntime () {return false;
    Public Boolean matches (method, Class Targetclass) {return true; } public Boolean matches (method, Class Targetclass, object[] args) {//should never be invoked as ISRU
        Ntime returns FALSE.
    throw new Unsupportedoperationexception (); }/** * Required to support serialization.
     Replaces with canonical * instance on deserialization, protecting Singleton pattern.
     * Alternative to overriding {@code equals ()}.
    */Private Object readresolve () {return INSTANCE; } @Override Public StriNg toString () {return "methodmatcher.true"; }
}

Next we begin to learn what spring AOP is all about
not yet ...

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.