Application examples and summary of SPRINGAOP

Source: Internet
Author: User
Tags modifier throw exception throwable

One: the background of AOP

During the interview, the interviewer asked me to explain what AOP was, didn't understand it, and looked it up on the road, AOP: aspect-oriented programming technology, confusing, Java is OOP: Object-oriented programming technology. Then I immediately looked at a few for the title: 1, what is the aspect-oriented programming technology, 2, why to face the aspect of programming technology; 3. What is the relationship with OOP?

First explain the second question: in our usual development process, you will certainly encounter the following several aspects: 1) permission check; 2) The core code of the business, 3) record the log. Then in the @service layer with the method of code accumulation, then the structure will be as follows.

@Servicepublic class myservice{@Resourceprivate coreservice coreservice @Resourceprivate logservice logservice;@ Resourceprivate Propertyservice Propertyservice; Code for authorization check code//core Business layer Code//logging  

Handling of exceptions
}

From the code structure above, we can see the following issues:

1.1, Code confusion: core business module and other non-core code intertwined, greatly affected the code of the module independent performance, not conducive to the maintenance of code, and the Division of labor is not clear cause code confusion.

1.2, redundant code: In fact, the permissions of the check, exception processing, log records can be independent of all services in a module to the public, written together resulting in code dispersion and redundancy.

Therefore, the aspect-oriented programming technology emerges.

Explain the first question: what is a tangent-oriented programming technique. Facets and pointcuts are the terms of the geometry, which can be understood here: The core business code process is likened to a bar, other log records, and permission checks are like facets of a crosscutting core business that need to accomplish some non-core business. Such as:

It can be seen that we define multiple facets, each of which completes its own non-core business, and one facet can accomplish multiple non-core operations.

1.3. Question three: What is the relationship to OOP?

AOP is implemented in a variety of ways, with Java seamlessly interfacing with a technology called ASPECTJ, and Spring AOP is not exactly the same as the ASPECTJ implementation, but functionally similar. The advent of AOP does solve the problem of separating the perimeter business code from the core business code, but it does not replace OOP, and if the advent of OOP is to modularize the coding problem, then AOP is the unified management of a class of issues involving many modules (see: About Spring AOP ( AspectJ) All that you should know, in fact, I also think of their relationship, but feel no this blog summed up very well.

II: The core concept of AOP

From the top right, you can see very well that the facets (Aspect) contain a tangent point (PointCut), a junction (Joinpoint), an additional notification (Advice), a weave (Weaving), and a (introduce) entry.

Package Springmvcmybatis.com.my.aop;import Org.aspectj.lang.annotation.Aspect;  Import Org.aspectj.lang.annotation.Around;  Import Org.aspectj.lang.annotation.Before;  Import Org.aspectj.lang.annotation.Pointcut;  Import Org.aspectj.lang.joinpoint;import Org.aspectj.lang.ProceedingJoinPoint;  Import Org.aspectj.lang.annotation.After;  Import org.aspectj.lang.annotation.AfterReturning;  Import org.aspectj.lang.annotation.AfterThrowing; Import Org.springframework.core.annotation.Order; @Aspect//Slice execution order @order (3) public class Myaoptest {@Pointcut (" Execution (* springmvcmybatis).      Addcontroller.addemp (..)) ")      private void Pointcutmethod () {} @Pointcut ("Execution (* springmvcmybatis.com.my.aop.userserviceimp.* (..))") private void Testaop () {}//* Declares a pre-notification, Joinpont is a static variable provided by Srpring, * The class name, method parameter, method name, etc. of the target method can be obtained by joinpoint parameter, this   Parameters are optional. */@Before ("Pointcutmethod () | | | TESTAOP () ") public void Dobefore (Joinpoint joinpoint) {System.out.println (" @BefoRe: Start adding--order=3 "); }//Declares the post-notification, if the type of result does not match the type of the parameter returned by the method executed by proceed, then this method will not be executed @AfterReturning (pointcut = "Pointcutmethod () | | | TESTAOP () ", returning =" result ") public void doafterreturning (String result) {System.out.println (" @AfterRe          Turning: Post-notification--order=3 ");      SYSTEM.OUT.PRINTLN ("---" + result + "---"); }//Declaration exception Notification @AfterThrowing (pointcut = "Pointcutmethod () | | | TESTAOP () ", throwing =" E ") public void doafterthrowing (Exception e) {System.out.println (" @AfterThrowing: Exception          Notice--order=3 ");      System.out.println (E.getmessage ()); }//Declare the final notification @After ("Pointcutmethod () | | |      TESTAOP () ") public void Doafter () {System.out.println (" @After: Final Notice--order=3 "); }/* * The declaration wrapping notification * parameter must be proceedingjoinpoint, through the object's proceed () method to execute the target function, * proceed () The return value is the return value of the surround notification, Proceedingjoinpoint is   interface, * Implement Joinpoint, so you can also get the target function class name, method name and other parameters. */@Around ("Pointcutmethod () | | | TESTAOP () ") Public Object Doaround (Proceedingjoinpoint pjp) throws Throwable {System.out.println ("@Around: Enter method---surround notification--order=3");          Object o = pjp.proceed ();          System.out.println ("@Around: Exit method---Surround notification--order=3");      return o; }    }

  

Here is an example of what I have written, combining examples to see these core concepts:

2.1, Aspect (Aspect): Is a class, inside defines the notice and the tangent point.

2.2, Tangent Point (PointCut): expression. is to tell the program to perform non-core business when it executes the core business.

2.3, notice (advice): Five kinds of notice method:

    • @Before: A pre-notification task that performs a notification definition before calling the target method
    • @After: A post notification that performs notification-defined tasks, regardless of the execution result, after the end of the target method execution
    • @After-returning: A post notification that executes the task of the notification definition if the execution succeeds after the target method execution finishes
    • @After-throwing: Exception notification, the task that executes the notification definition if an exception is thrown during the execution of the target method
    • @Around: Surround notifications, both before and after the target method is executed, to perform the tasks defined by the notification.

The order of execution of the five notification methods:

Order of execution under normal circumstances:

@Around: Enter method---Surround notification--order=3@before: Start adding--order=3============ Execute business method Finduser, find the user is: Zhang San ============= @Around: Exit method---Surround notification--order=3@after: Final notification--order=3@afterreturning: Post notification--order=3---Zhang San---
Order of execution in exceptional cases: @Around: Enter method---Surround notification--order=3@before: Start adding--order=3============ Execute business method adduser============= @After: Final notification--order=3@afterthrowing: Exception notification--order=3null

Three: tangent expression.

There are many kinds of expressions, such as method signature expression, type signature expression, and other expressions, I have only used the previous two, the other is useless, do not introduce, if these two expressions can not solve the problem, I refer to the blog.

3.1: Method signature Expression
Execution (< modifier pattern >?< return type mode >< fully qualified name mode for the class of the method > (< parameter mode >) < exception mode;?) Execution (Modifiers-pattern ret-type-pattern fully-qualified-class-name (param-pattern) Throws-pattern?)  
In fact, if the simple given this expression is still not easy to remember, the following comparison of the definition of the method to remember, a Java method of the entire definition of the way can be expressed as follows:
public string SpringMVCmybatic.com.my.aop.UserServiceImp (string a, int b) throw exception{}
    • Modifier-pattern.: Represents the modifier of a method, which is optional;
    • Ret-type-pattern: Represents the return value of a method, which corresponds to a String
    • The fully qualified name of the class in which the Fully-qualified-class-name method resides; the corresponding is SPRINGMVCMYBATIC.COM.MY.AOP.USERSERVICEIMP
    • Param-pattern: A parameter that represents a method, which corresponds to a String a, an int b
    • Throws-pattern: Represents the exception that is thrown by the method, is optional, and the corresponding is the throw Exception

3.2:&&,| |,!

  @Around ("Pointcutmethod () | | | TESTAOP () ") Public      Object Doaround (Proceedingjoinpoint pjp) throws Throwable {          System.out.println (" @Around: Access Method---surround notification ");          Object o = pjp.proceed ();          System.out.println ("@Around: Exit Method---surround Notification");          return o;      }  

Expressions can be filtered in the same way as, or, not.

Four: Order of execution for multiple pointcuts

In the above example, the order=3 is defined, a slice is recreated, the order=6 is defined, and the result is:

@Around: Enter method---Surround notification--order=3@before: Start adding--order=3@around: Enter method---Surround notification--order=6@before: Start adding--order=6============ Execute business method Finduser, find the user is: Zhang San ============= @Around: Exit method---Surround notification--order=6@after: Final notification--order=6@afterreturning: Post Notification--order=6---Zhang San---@Around: Exit method---Surround notification--order=3@after: Final notification--order=3@afterreturning: Post notification--order=3--- Zhang San---@Around: Enter method---Surround notification--order=3@before: Start adding--order=3@around: Enter method---Surround notification--order=6@before: Start adding--order=6======= ===== execution Business Method adduser============= @After: Final notification--order=6@afterthrowing: Exception notification--order=6null@after: Final notification--order=3@ Afterthrowing: Exception Notification--order=3null

From the results you can see that the smaller the order, the first execution, after the execution of the order the smaller the more after the launch. The following figure is summarized:

"Reference Blog"

1, http://blog.csdn.net/javazejian/article/details/56267036/

2, http://blog.csdn.net/qqxhwwqwq/article/details/51678595

Application examples and summary of 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.