What is AOP?

Source: Internet
Author: User
Tags add time

David
Links: https://zhuanlan.zhihu.com/p/21273202
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

What is AOP?

One of the basic principles of software engineering is called "Separation of concerns" (Concern separation), and popular understanding is that different issues are assigned to different parts to solve, with each part focused on solving their own problems. These days the Internet also emphasizes to focus on every day!

This is actually a kind of "divide and conquer" or "classify" the thought, the person solves the complex problem the ability is limited, therefore in order to control the complexity, we often must solve the problem to disassemble, the disassembly simultaneously establishes each part relations, conquer after the whole question also solves. Human thinking, the design of complex systems, computer algorithms, can attest to this idea. Well, this is a relationship with AOP.

Aspect-oriented programming (Aspect oriented PROGRAMMING,AOP) is actually a kind of separation of concerns technology, in the field of software engineering is once a very hot research field. Our software development often refers to a word called "business logic" or "business function", our code is mainly to implement a specific business logic. But we often can't focus on the business logic, such as when we write business logic code, but also write transaction management, caching, logging, and so the general function, and each business function to be mixed with these business functions, pain! As a result, AOP technology has emerged in order to isolate the focus of business functions from the focus of the generalization function. The code implementations of these generalized functions correspond to the facets we say (Aspect).

After the business function code and the cut-off code are separated, the responsibility is clear, the developer can focus on solving the problem, the code can be organized gracefully, the design of higher cohesion low coupling (the ultimate goal Ah! )。 However, please note that the code is separate, how can we guarantee the integrity of the function? Your business functions still require features such as transactions and logs, where the slices eventually need to be merged (jargon called Weaving, Weave) into business functions. How do you do it? There are three ways to deal with the underlying techniques of AOP:

    1. Compile-time weaving: When the code is compiled, the cut-off code is fused in, generating the full functionality of the Java bytecode, which requires a special Java compiler, ASPECTJ belongs to this class
    2. Class loading: When Java bytecode is loaded, the byte code of the slice is fused in, which requires a special ClassLoader, ASPECTJ and Aspectwerkz to implement the class loading
    3. Run-time Weaving: In the run-time, it is this approach that spring uses to invoke cutting-plane code to enhance the business function by means of a dynamic proxy. Dynamic proxies have a performance overhead, but the advantage is that you don't need a special compiler and ClassLoader for God's horse, just follow the way you write plain Java programs!
A scene

The next example! David was satisfied with the example of the local tyrants boss booking, so he decided to continue with the example.

Boss when booking a ticket, we want to be able to record the time it takes to book a ticket, and record the log (here we simply print the information of the predetermined success in the console).

Let's look at the practice of ordinary youth:

package com.tianmaying.aopdemo;public class Boss {    private BookingService bookingService;    public Boss() {        this.bookingService = new QunarBookingService();    }    //...    public void goSomewhere() {        long start = System.currentTimeMillis();                //订机票        boolean status = bookingService.bookFlight();        //查看耗时        long duration = System.http://tianmaying.com/tutorial/spring-ioc#/1() - start;        System.out.println(String.format("time for booking flight is %d seconds", duration));        //记录日志        if (status) {            System.out.println("booking flight succeeded!");        } else {            System.out.println("booking flight failed!");        }    }}

We see that while booking tickets, we also have to deal with the time-consuming and logging, the attention of the matter too much, head big AH. And after the project is big, in addition to booking tickets, many business functions have to write similar code. Let AOP come and save us!

Scenarios that use AOP

Instead of the code in the IOC example, we let Bookingservice's Bookflight () method return a Boolean value indicating whether the reservation was successful. So we can show how to get the return value of the tangent method.

What do we do with AOP, David today gives you the secret to understanding AOP through the 3W approach (what-where-when).

    • What:what Of course refers to the time slice! First we separate the code for the two functions of recording consumption time and logging, and we can make two facets, named Timerecordingaspect and Logaspect.
    • Where: Where does the weaving of facets occur? The target object for the tangent plane (target) is Smartboss (different from the boss)! There is also a key concept called the Pointcut (Pointcut), which in this scenario refers to the application of facets when Smartboss invokes any method. Obviously, we want to enhance the Bookflight () method, that is, where the Bookflight method is called, we add Time records and logs.
    • When: What time is it woven into? This involves the timing of the weaving, which we can weave before the Bookflight () is performed, weave in after execution, or both before and after execution. The concept of when is called Notice (Advice) in professional terms.

After understanding the 3W, take a look at the code, first logaspect:

Insert a section, pom file do not forget to introduce spring AOP related dependencies:

    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context</artifactId>        <version>4.2.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-aop</artifactId>        <version>4.2.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.aspectj</groupId>        <artifactId>aspectjweaver</artifactId>        <version>1.8.5</version>    </dependency>      <dependency>        <groupId>org.aspectj</groupId>        <artifactId>aspectjrt</artifactId>        <version>1.8.5</version>    </dependency>

Logaspect

package com.tianmaying.aopdemo.aspect;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;@Aspect //1@Componentpublic class LogAspect {    @Pointcut("execution(* com.tianmaying.aopdemo..*.bookFlight(..))") //2    private void logPointCut() {    }    @AfterReturning(pointcut = "logPointCut()", returning = "retVal") //3    public void logBookingStatus(boolean retVal) {  //4        if (retVal) {            System.out.println("booking flight succeeded!");        } else {            System.out.println("booking flight failed!");        }    }}

Let's look at this code:

1 by means of a @apsect callout, the logaspect is a facet that solves what the problem is. 2 defines where the problem is by defining a method labeled @pointcut, "Execution (* Com.tianmaying.aopdemo. *.bookflight (..)) " Indicates that the name of the Com.tianmaying.aopdemo package or sub-package called Bookflight is the pointcut! The syntax for defining pioncut is unknown here, and David is here to tell you what it does when it works: solving the WHERE problem! 3 A @afterreturning callout indicates that the slice is woven after the bookflight () call, which is a afterreturning type of advice, note that the returning property can be obtained bookflight () 's return value. 4 here defines the implementation of the section function of the code, after so a flash maneuvers, the last write log code came here!

Look again at Timerecordingaspect:

Timerecordingaspect:

 package com.tianmaying.aopdemo.aspect;import Org.aspectj.lang.proceedingjoinpoint;import Org.aspectj.lang.annotation.around;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.pointcut;import Org.springframework.stereotype.Component, @Aspect @componentpublic class Timerecordingaspect {@Pointcut ("Execution ( * Com.tianmaying.aopdemo.    *.bookflight (..)) ") private void Timerecordingpointcut () {} @Around ("Timerecordingpointcut ()")//1 public Object recordtime (Proceedi        Ngjoinpoint pjp) throws Throwable {//2 long start = System.currenttimemillis (); Object RetVal = Pjp.proceed ();        3 Long Duration = System.currenttimemillis ()-Start;        System.out.println (String.Format ("Time for booking flight is%d seconds", duration));    return retVal; }}
    • Unlike Logaspect, because we have to calculate the time-consuming of bookflight (), we have to go to the code before and after the call to figure out the difference between the two. So, at 1, we define a around type of advice.
    • 2 is the method to implement Aroundadvice, and its method parameters and return values are fixed notation.
    • 3 is also a fixed notation, indicating that the target method (that is, bookflight ()) of the call, pay attention to do not leak, the original method will not be called out, usually not the result you want!

Look back to Smartboss code, more simple than Boss, Gosomewhere () method only left a statement, cool off the slag Ah, only pay attention to booking tickets, other things are f**k off!

package com.tianmaying.aopdemo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class SmartBoss {    private BookingService bookingService;        //...    public void goSomewhere() {        bookingService.bookFlight();    }}

Of course, in order for the code to run, you also need to add the @enableaspectjautoproxy annotation to the app class so that when spring starts, it scans for AOP-related annotations and helps us perform the weaving process when creating objects!

Back to Definition

Finish the example! Now let's take a look at the definitions of the terms in AOP, and at this time understand these concepts, you should not feel cold, you should have a "ya!" The feeling!

    • Tangent (Aspect): Refers to the common functionality of the code implementation, such as we demonstrated above the time record slices, log slices, they are common Java class: Timerecordingaspect and Logaspect.

    • Target object: The object to be woven into the plane, ctripbookingservice in the example, with AOP, which can focus on the core business logic code!

    • Pointcut (Pointcut): Defines where notifications should be cut into, spring-supported pointcuts are method invocations, and Pointcut definitions can use regular expressions to describe what type of method invocation. @Pointcut is used to define a pointcut.

    • Notification (Advice): A tangent is a class, and the notification is the method in the class and how the method weaves into the target method (in @afterreturning and @around notation). Our example shows only two types of notifications, which can be divided into 5 types according to the way they are woven into the target method:

      • Pre-notification (before)
      • Post Notification (afterreturning)
      • Exception Notification (afterthrowing)
      • Final notification (after)
      • Surround Notification (Around)
    • Weaving (Weaving): The process of AOP implementation, the process of applying facets to a target object, creating a new proxy object, and for spring, when initializing the object in the context, the weaving operation is completed.

Now you should understand the key knowledge and core principles of AOP in spring, and the rest is to learn the knowledge of each part in the 3W framework that David gives you, such as the notation of different types of notifications, the pointcut of various types of definitions, the passing of parameters between facets and target objects, and so on. Of course, the most important thing is to hurry up and use it in practice!

What is AOP?

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.