Spring framework learning [AOP Basics]

Source: Internet
Author: User

1. basic concept of AOP: Aspect-Oriented Programming, short for Aspect-Oriented Programming, Aspect is a new modular mechanism, it is used to describe the cross-concern (crosscutting concern) distributed in objects, classes, or methods. Separating the cross-concern from the concerns is the core of Aspect-Oriented Programming. The separation of focus makes the code that solves problems in a specific domain independent from the business logic. The code of the business logic no longer contains calls to the code of the problem in a specific domain, the relationship between business logic and problems in specific fields is encapsulated and maintained through aspects, so that changes originally dispersed throughout the application can be well managed.

2. Differences between AOP and OOP:

Aspect-oriented programming (AOP) and Object-Oriented Programming (OOP) are literally similar, but they are two design ideas oriented to different fields. OOP abstracts and encapsulates entities, attributes, and actions in the business processing process to achieve clearer and more efficient logical unit division. AOP extracts the aspect of the business processing process. It faces a certain step or stage in the processing process, in order to obtain the isolation effect of low coupling between different parts in the logical process.

3. Common AOP technologies and implementations:

Common AOP technologies include:

(1). AspectJ: source code and bytecode level aspect knitting machine. You need to use a new language different from that of java.

(2). AspectWerkz: AOP framework, which uses the bytecode dynamic braid and XML configuration.

(3). JBoss-AOP: an AOP framework based on the interceptor and metadata and runs on the JBoss application server.

Some implementation technologies used in AOP include :,

(1). BCEL: Byte-Code Engineering Library, Java bytecode operation class Library.

(2). ipvsist: Java bytecode operation class library, a subproject of JBoss.

4. Common Terms for Aspect-oriented programming (AOP:

(1). Aspect: the Aspect declaration is similar to the class declaration in Java. Aspect contains some Pointcut entries and the Advice notification for corresponding operations on the Pointcut.

(2 ). join point Joint point: a point that is clearly defined in a program. Typical examples include method calls, access to class members, and execution of exception handling program blocks, it can also nest other connection points, jointpoint.

(3 ). pointcut: indicates a set of connection points (jointpoint). These connection points are combined by logical links, or centralized by wildcard or regular expressions, it defines where the corresponding operation processing notification Advice will occur.

(4 ). notification Advice: Advice defines the specific operations and processing of the program points defined in the pointcut entry point, it uses before, after, and around to distinguish whether the code is executed before, after, or in place of each start point.

(5). Target object: the Target object of the proxy, that is, the Target object to which the aspect is applied.

(6) woven into Weave: it refers to the process of applying the cut surface to the target object and causing the creation of the proxy object.

5. Architecture of AOP:

The AOP architecture defined by the AOP alliance is as follows:

Level 3 Language and development environment: Basic refers to the objects to be added or target objects; aspect usually includes adding applications to the Foundation; configuration refers to the configuration environment or weaving configuration provided in the AOP system, by configuring AOP, you can combine the basic and cut surface to achieve the goal object weaving by the cut surface.

Level 2 aspect-oriented systems: the configuration model, logical configuration, and AOP model provide support for the language and development environment of the policy, the main function is to convert, abstract, and encapsulate the target object, aspect, and configuration to an aspect-oriented logic model using the APIs of AOP.

Level 1 bottom-layer knitting implementation module: It mainly refers to the implementation technology of the AOP model abstracted and encapsulated by the aspect-oriented system into the target object to be enhanced.

6. Advice notification:

Advice notification is an interface defined by the AOP alliance. It defines that when the connection point is intercepted, corresponding processing operations are performed to provide the weaving interface for the aspect enhancement. In Spring AOP, notifications mainly describe Spring AOP's injection behavior around method calls. Spring AOP notifications extend the notification interfaces of the AOP alliance, provides pre-notification BeforeAdvice, post-Notification AfterReturnAdvice, final notification AfterAdvice, and exception notification ThrowAdvice.

(1). Take a method as an example to explain the types of notifications in Spring:

[Java]View plaincopy
  1. Public return type method name (parameter list) {--> pre-processing code for surround notification method --> pre-notification
  2. Try {method implementation (method body ).......
  3. Method post-processing code --> post-Notification} Catch (exception type e ){
  4. Exception Handling ...... --> Exception notification} finally {
  5. Final Processing proxy ...... --> Final notification}
  6. }

    (2). BeforeAdvice:

    A. the source code of the pre-notification is as follows:

    [Java]View plaincopy
    1. Package org. springframework. aop; import org. aopalliance. aop. Advice;
    2. Public interface BeforeAdvice extends Advice {}

      Advice is the notification interface provided by the AOP alliance.

      B. Method of subinterface of pre-notification MethodBeforeAdvice:

      In the inheritance relationship of the pre-notification BeforeAdvice, the pre-notification MethodBeforeAdvice is defined as the pre-enhancement interface method set for the generation enhancement target method. The source code is as follows:

      [Java]View plaincopy
      1. Public interface MethodBeforeAdvice extends BeforeAdvice {// callback method of the pre-method notification, called before the target object method is called
      2. // The method parameter is the reflection Object of the target Method, and The args is the input parameter array void before (method, Object [] args, Object target) throws Throwable;
      3. }

        C. CountingBeforeAdvice:

        Methods There are many implementation classes for the pre-notification MethodBeforeAdvice interface. We take the simplest CountingBeforeAdvice as an example to analyze the specific operations performed by the pre-notification method. The source code of CountingBeforeAdvice is as follows:

        [Java]View plaincopy
        1. Public class CountingBeforeAdvice extends MethodCounter implements MethodBeforeAdvice {// method of implementing the method of pre-notification to the MethodBeforeAdvice Interface
        2. Public void before (Method m, Object [] args, Object target) throws Throwable {// The count Method of the parent class MethodCounter is called to count the number of times the Method is called.
        3. Count (m );}
        4. } The source code of the CountingBeforeAdvice parent class MethodCounter is as follows:
        5. Public class MethodCounter implements Serializable {// method name-> map set of the number of method calls, storing the number of method calls
        6. Private HashMap Map = new HashMap (); // The total number of calls to all methods
        7. Private int allCount; // count the number of method calls, CountingBeforeAdvice call entry
        8. Protected void count (Method m) {count (m. getName ());
        9. } // Count the number of calls to the method with the specified name
        10. Protected void count (String methodName) {// obtain the number of calls to a method with the specified name from the Method Name> Number of call times set
        11. Integer I = map. get (methodName); // if the number of calls is not null, add 1 to the number of calls. If the number of calls is null, set the number of calls to 1.
        12. I = (I! = Null )? New Integer (I. intValue () + 1): new Integer (1); // reset the number of method calls saved in the Set
        13. Map. put (methodName, I); // The total number of calls to all methods plus 1
        14. ++ AllCount ;}
        15. // Obtain the number of calls to the method with the specified name. public int getcils (String methodName ){
        16. Integer I = map. get (methodName); return (I! = Null? I. intValue (): 0 );
        17. } // Obtain the total number of calls to all methods
        18. Public int getcils () {return allCount;
        19. } Public boolean equals (Object other ){
        20. Return (other! = Null & other. getClass () = this. getClass ());}
        21. Public int hashCode () {return getClass (). hashCode ();
        22. }}

          (3). Final notification AfterAdvice:

          A. the source code of the final notification AfterAdvice is as follows:

          [Java]View plaincopy
          1. Public interface AfterAdvice extends Advice {}

            Like the pre-notification, the final notification inherits the Advice interface defined by the AOP alliance.

            B. Post-Notification AfterReturningAdvice FOR THE subinterface of the final notification:

            In the inheritance system of the final notification, the post-Notification AfterReturningAdvice interface inherits the final notification interface. The source code is as follows:

            [Java]View plaincopy
            1. Public interface AfterReturningAdvice extends AfterAdvice {// callback Method for post-notification. This method is called after the call of the target method object ends and a success response is returned.
            2. // The returnValue parameter is the return value of the target method object, the method parameter is the target method object, and The args is the input parameter of the target method object.
            3. Void afterReturning (Object returnValue, Method method, Object [] args, Object target) throws Throwable ;}

              C. Implementation class CountingAfterReturningAdvice of post-notification:

              The post-Notification API AfterReturningAdvice has many implementation classes. We use the CountingAfterReturningAdvice class as an example to analyze the specific post-Notification operations:

              [Java]View plaincopy
              1. Public class CountingAfterReturningAdvice extends MethodCounter implements AfterReturningAdvice {// callback method for implementing post-Notification AfterReturningAdvice
              2. Public void afterReturning (Object o, Method m, Object [] args, Object target) throws Throwable {// call the count Method of the parent MethodCounter class, and count the number of calls of the Method
              3. Count (m );}
              4. }

                (4). ThrowAdvice:

                A. source code for exception notification ThrowAdvice

                The exception notification ThrowAdvice interface also inherits the final notification AfterAdvice. The source code is as follows:

                [Java]View plaincopy
                1. Public interface ThrowsAdvice extends AfterAdvice {}

                  B. CountingThrowsAdvice:

                  The exception notification does not specify the interface method to be implemented. It is called back when an exception is thrown. This callback is implemented by AOP Using the JDK reflection mechanism, the following uses CountingThrowsAdvice as an example to analyze the usage of exception notifications:

                  [Java]View plaincopy
                  1. Public static class CountingThrowsAdvice extends MethodCounter implements ThrowsAdvice {// The callback method when an I/O exception is thrown. The number of times an exception is called is counted.
                  2. Public void afterThrowing (IOException ex) throws Throwable {count (IOException. class. getName ());
                  3. } // The callback method when an UncheckedException type exception is thrown. The number of times an exception is called is counted.
                  4. Public void afterThrowing (UncheckedException ex) throws Throwable {count (UncheckedException. class. getName ());
                  5. }}

                    7. Pointcur entry point:

                    The Pointcut entry point determines the connection point to which the Advice should act, that is, the Pointcut entry point is used to define the method set that requires AOP enhancement in the target object. The selection of these sets can be completed according to certain rules.

                    Pointcut usually indicates the identification method. The methods to be enhanced can be identified by a regular expression or matched according to the specified method name.

                    (1) Pointcut source code:

                    [Java]View plaincopy
                    1. Public interface Pointcut {// get the class filter
                    2. ClassFilter getClassFilter (); // you can call this operation to obtain the matching start point.
                    3. MethodMatcher getMethodMatcher (); // The standard entry point instance that matches the total number of entries.
                    4. Pointcut TRUE = TruePointcut. INSTANCE ;}

                      (2) Pointcut interface implementation class JdkRegexpMethodPointcut:

                      View the inheritance system of Pointcut entry points, and find that there are many implementation classes of Pointcut entry points, such as AnnotationMatchingPointcut for annotation configuration and JdkRegexpMethodPointcut for regular expressions. Let's take JdkRegexpMethodPointcut as an example, analyze the specific implementation of Entry Point Matching. The source code is as follows:

                      [Java]View plaincopy
                      1. Public class JdkRegexpMethodPointcut extends actregexpmethodpointcut {// regular expression mode to be compiled
                      2. Private Pattern [] compiledPatterns = new Pattern [0]; // The regular expression Pattern to be excluded during compilation
                      3. Private Pattern [] compiledExclusionPatterns = new Pattern [0]; // initializes the given Pattern string array to the compiled regular expression Pattern.
                      4. Protected void initPatternRepresentation (String [] patterns) throws PatternSyntaxException {this. compiledPatterns = compilePatterns (patterns );
                      5. } // Initialize the given pattern string array to the regular expression pattern to be excluded during compilation
                      6. Protected void initExcludedPatternRepresentation (String [] excludedPatterns) throws PatternSyntaxException {this. compiledExclusionPatterns = compilePatterns (excludedPatterns );
                      7. } // Use a regular expression to match a given name
                      8. Protected boolean matches (String pattern, int patternIndex) {Matcher matcher = this. compiledPatterns [patternIndex]. matcher (pattern );
                      9. Return matcher. matches ();}
                      10. // Use the regular expression to be excluded to match the given name protected boolean matchesExclusion (String candidate, int patternIndex ){
                      11. Matcher matcher = this. compiledExclusionPatterns [patternIndex]. matcher (candidate); return matcher. matches ();
                      12. } // Compile the given string array into a regular expression mode
                      13. Private Pattern [] compilePatterns (String [] source) throws PatternSyntaxException {Pattern [] destination = new Pattern [source. length];
                      14. For (int I = 0; I <source. length; I ++) {destination [I] = Pattern. compile (source [I]);
                      15. } Return destination;
                      16. }}

                        From the source code analysis, we can see that the basic function of using a regular expression to match Pointcut entries is to judge whether the method name matches the regular expression.

                        8. Advisor:

                        After completing the design and development of the Advice and the entry Point for the target object method, you need an object to combine the target object, the enhancement behavior, and the entry Point, the notification Advisor is an object that implements this function. It defines where the methods of the target objects use the added behavior.

                        (1). Advisor:

                        The source code of Advisor is as follows:

                        [Java]View plaincopy
                        1. Public interface Advisor {// get the aspect notification Advice
                        2. Advice getAdvice (); // determines whether the notification is related to a specific instance object.
                        3. Boolean isPerInstance ();}

                          (2) Advisor ultpointcutadvisor, implementation class of Advisor:

                          View the inheritance system of the Advisor notificator and find that there are many implementation classes of the Advisor. Let's take the most common defapointpointcutadvisor as an example to analyze the working principle of the notificator.

                          A. defapointpointcutadvisor source code is as follows:

                          [Java]View plaincopy
                          1. Public class defapointpointcutadvisor extends actgenericpointcutadvisor implements Serializable {// default entry point
                          2. // Pointcut. TRUE is defined as: Pointcut TRUE = TruePointcut. INSTANCE; private Pointcut pointcut = Pointcut. TRUE;
                          3. // No parameter constructor. Create an empty notifier public defapointpointcutadvisor (){
                          4. } // Create a notifier that matches all methods
                          5. Public defapointpointcutadvisor (Advice advice) {this (Pointcut. TRUE, advice );
                          6. } // Create a notification device for the specified entry point and notification
                          7. Public defapointpointcutadvisor (Pointcut pointcut, Advice advice) {this. pointcut = pointcut;
                          8. SetAdvice (advice );}
                          9. // Set the entry point public void setPointcut (Pointcut pointcut) for the notification ){
                          10. This. pointcut = (pointcut! = Null? Pointcut: Pointcut. TRUE );}
                          11. // Obtain the entry point public Pointcut getPointcut (){
                          12. Return this. pointcut ;}
                          13. Public String toString () {return getClass (). getName () + ": pointcut [" + getPointcut () + "]; advice [" + getAdvice () + "]";
                          14. }}

                            In the above source code, the default start point of the notifier is Pointcut.TRUE, Pointcut.TRUEIt is defined as: Pointcut TRUE = TruePointcut. INSTANCE;

                            B. TruePointcut:

                            TruePointcut is the default entry point of the notifier. Its main function is to configure the default class filter and method matching, that is, to define which methods Spring AOP applies to. The source code is as follows:

                            [Java]View plaincopy
                            1. Class TruePointcut implements Pointcut, Serializable {// INSTANCE is a constant single piece of the TruePointcut class, that is, there is only one such piece in the entire application,
                            2. // The Second INSTANCE Object will not be created to ensure the uniqueness of the INSTANCE Object. The single-State model public static final TruePointcut INSTANCE = new TruePointcut ();
                            3. // Single-State mode constructor private TruePointcut (){
                            4. } // Obtain the class filter of the entry point
                            5. Public ClassFilter getClassFilter () {return ClassFilter. TRUE;
                            6. } // Obtain the method matching of the entry point
                            7. Public MethodMatcher getMethodMatcher () {return MethodMatcher. TRUE;
                            8. } // Method for retrieving single-State mode objects
                            9. Private Object readResolve () {return INSTANCE;
                            10. } Public String toString (){
                            11. Return "Pointcut. TRUE ";}
                            12. }

                              From the source code of TruePointcut, we can see that TrueClassFilter is used as the class filter to match any class, And TrueMethodMatcher is used as the method matcher to match any method. Next we will continue to analyze the TrueClassFilter class filters and TrueMethodMatcher method matchers.

                              C. TrueClassFilter:

                              TrueClassFilter is the default class filter for the default entry point. It mainly tells the entry point which classes are enhanced. The source code is as follows:

                              [Java]View plaincopy
                              1. Class TrueClassFilter implements ClassFilter, Serializable {// single-State Mode
                              2. Public static final TrueClassFilter INSTANCE = new TrueClassFilter (); // Construction Method of the single-State Mode
                              3. Private TrueClassFilter (){}
                              4. // The method of filtering matching classes by the entry point. By default, public boolean matches (Class clazz ){
                              5. Return true ;}
                              6. // Method for retrieving single-State mode objects private Object readResolve (){
                              7. Return INSTANCE ;}
                              8. Public String toString () {return "ClassFilter. TRUE ";
                              9. }}

                                D. TrueMethodMatcher:

                                TrueMethodMatcher is the default method matcher for the default entry point. It mainly tells the entry point which methods are enhanced. The source code is as follows:

                                [Java]View plaincopy
                                1. Class TrueMethodMatcher implements MethodMatcher, Serializable {// single-State Mode
                                2. Public static final TrueMethodMatcher INSTANCE = new TrueMethodMatcher (); // method for constructing the single-State Mode
                                3. Private TrueMethodMatcher (){}
                                4. // The public boolean isRuntime (){
                                5. Return false ;}
                                6. // Called when the start point matches the Method. By default, all methods are matched. public boolean matches (method Method, Class targetClass ){
                                7. Return true ;}
                                8. // The call during running will throw an exception public boolean matches (Method method, Class targetClass, Object [] args ){
                                9. Throw new UnsupportedOperationException ();}
                                10. // Method for retrieving single-State mode objects private Object readResolve (){
                                11. Return INSTANCE ;}
                                12. Public String toString () {return "MethodMatcher. TRUE ";
                                13. }}

                                  From the source code of the method matcher above, we can see that the starting point does not support running-time matching when matching the method. If matching is performed during running, an exception is thrown.

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.