Spring frame--AOP (aspect-oriented programming) detailed

Source: Internet
Author: User
Tags modifier

 1 AOPOverview

AOP (aspect-oriented programming, aspect-oriented programming ): is a new methodology for traditional OOP ( Object-oriented programming, Object-oriented programming ) complements.

The main object of the AOP programming operation is the tangent plane (aspect), while the facets are modular crosscutting concerns .

When you apply AOP programming, you still need to define public functionality, but you can clearly define where the feature is applied, how it is applied, and you do not have to modify the affected classes. Such a crosscutting concern is modularized into a special class -a class that we often call "facets."

Benefits of AOP:

0 Each thing logic in one place, code is not scattered, easy to maintain and upgrade

0 business modules are more concise and contain only core code

2 AOPTerminology2.1 crosscutting concerns

the same class of non-core business extracted from each method. (Process non-core business from extraction to method)

2.2Facets(Aspect)

A class that encapsulates information about crosscutting concerns , each of which is represented as a notification method.

2.3Notice(Advice)

The specific work to be done by the facets

2.4Target(Target)

The object being notified

2.5Agent(Proxy)

Proxy Objects created after the notification is applied to the target object

2.6Connection Point( Joinpoint)

The specific embodiment of crosscutting concerns in program code that corresponds to a specific location where the program executes. For example: before a method call, after a call, after a method catches an exception, and so on.

In your application, you can use the horizontal two coordinates to locate a specific connection point:

2.7entry point(pointcut):

the way to locate the connection point. Each class has multiple connection points in its methods, so the connection point is something that exists in the class. If you think of a connection point as a record in a database, the pointcut is the query condition --AOP can be positioned to a specific connection point through a pointcut.

pointcuts are described by the Org.springframework.aop.Pointcut interface, which uses classes and methods as query criteria for connection points.

3 AspectJ3.1 Introduction

AspectJ:the most complete and popular AOP Framework in theJava community .

in the Spring2.0 or later, you can use AOP based on AspectJ annotations or XML-based configuration .

3.2in theSpringenabled inAspectJAnnotation Support① ImportJARPackage

Aopalliance.jar

Aspectj.weaver.jar

Spring-aspects.jar

② IntroductionAOPname Space

③ Configuration

<aop:aspectj-autoproxy>

when When the Spring IOC container detects the <aop:aspectj-autoproxy> elements in the bean configuration file , it automatically AspectJ Facets match the Bean Create an agent

3.3withAspectjAnnotation declaration Facets

① to declare >spring font-family ASPECTJ Slice, just in ioc The slice is declared as in the container. bean example. ② when initializing >spring in style= font-family " container Style= "Font-family:calibri" >ASPECTJ after plane, spring IOC ASPECTJ bean Create an agent.

③ in the AspectJ Annotation, the slice is just a Java class with @Aspect annotations , which often contains a lot of notifications.

④ notifications are simple Java methods that annotate some kind of annotation .

⑤AspectJ supports 5 Types of notification annotations:

[1] @Before: Pre-notification, execution before method execution

[2] @After: Post notification, executed after method execution

[3] @AfterRunning: Returns a notification, executed after the method returns the result

[4] @AfterThrowing: Exception notification, executed after the method throws an exception

[5] @Around: Surround notification, around method execution

4 Pointcut Expression 4.1 effect

Locates one or more specific connection points in the form of an expression .

4.2 Syntax details ① syntax format for pointcut expressions

Execution ([ permission modifier ] [ return value type ] [ Simple class name / full class name ] [ method Name ] ([ parameter list ] )

② Illustrative examples

An expression

Execution (* com.atguigu.spring.ArithmeticCalculator. *(..))

Meaning

all methods declared in the Arithmeticcalculator interface.

The first "*" represents an arbitrary modifier and any return value.

The second "*" represents an arbitrary method.

" . "matches any number, any type of argument.

If the target class, interface and the slice class in the same package can omit the package name.

An expression

Execution ( public * arithmeticcalculator.* (..))

Meaning

all public methods of the Arithmeticcalculator interface

An expression

Execution (public double arithmeticcalculator.* (..))

Meaning

method of returning a double type value in the Arithmeticcalculator interface

An expression

Execution (public double arithmeticcalculator.* (double,..))

Meaning

The first argument is a method of type Double.

" . "matches any number, any type of argument.

An expression

Execution (public double arithmeticcalculator.* (double, double))

Meaning

Parameter type double, method of type double

③ inAspectJ, the pointcut expression can be passed through the&&","||","!"and other operators together.

An expression

Execution (* *.add (int,..)) || Execution (* *.sub (int,..))

Meaning

An add method or sub method with the first argument of type int in any class

4.3 pointcut expressions are applied to the actual slice class

5 Current connection Point Details 5.1 overview

pointcut expressions typically locate a set of methods on a macro level, and together with the annotations of a specific notification, the corresponding connection point can be determined. So, for a specific connection point, we may be concerned with some specific information about the connection point, such as the method name of the method where the current connection point is located, the current parameter value passed in, and so on. This information is encapsulated in the instance object of the Joinpoint interface.

5.2 Joinpoint

6 Notice 6.1 Overview

L The operation to be performed on the specific connection point.

L A slice can include one or more notifications.

L Notice that the value of the annotation used is often a pointcut expression.

6.2 Front-facing notifications

L Pre-notification: notification to be performed prior to method execution

L use @Before annotations

6.3 Post Notification

L Post notification: The post notification is executed after the connection point is completed, that is, when the connection point returns a result or throws an exception

L use @After annotations

6.4 Return Notification

L return Notification: The post notification executes regardless of whether the connection point is returning normally or throws an exception. If you want to log only when the connection point is returned, you should use the return notification instead of the post notification.

L use @AfterReturning annotations

L ACCESS the return value of the connection point in the return notification

    • In the return notification, the return value of the connection point can be accessed as long as the returning attribute is added to the @AfterReturning annotation. The value of this property is the parameter name that is used to pass in the return value
    • You must add a parameter with the same name in the signature of the notification method. At run time, Spring AOP passes the return value through this parameter
    • The original pointcut expression needs to appear in the Pointcut property

6.5 Exception Notifications

L Exception Notification: Exception notification is only performed when the connection point throws an exception

L Add the throwing property to the @AfterThrowing annotation, or access the exception thrown by the connection point. throwable is the top-level parent class for all errors and exception classes, so you can catch any errors and exceptions in the exception notification method.

L If you are only interested in a particular type of exception, you can declare the parameter as the parameter type of the other exception. The notification is then executed only if the exception of the type and its subclasses is thrown

6.6 Surround Notification

The surround notification is the most powerful of all notification types, provides full control over connection points, and even controls whether or not to perform connection points.

L for surround notifications, the parameter type of the connection point must be proceedingjoinpoint. It is a Sub-interface of the joinpoint, allowing control over when to execute and whether to execute a connection point.

L need to explicitly call Proceedingjoinpoint 's Proceed () method in the surround notification to execute the proxied method. Forgetting to do so causes the notification to be executed, but the target method is not executed.

Note: The method that surrounds the notification needs to return the result after the target method executes, that is, call joinpoint.proceed (); return value, or a null pointer exception will occur.

6.7 Reusing Pointcut definitions

When writing AspectJ slices, you can write pointcut expressions directly in the notification annotations. However, the same pointcut expression may appear repeatedly in multiple notifications.

L in AspectJ facets, you can declare a pointcut as a simple method by @Pointcut annotations. The method body of a pointcut is usually empty, because it is unreasonable to mix the pointcut definition with the application logic.

The access control of the Pointcut method also controls the visibility of this pointcut. If pointcuts are to be used in multiple facets, it is best to concentrate them in a common class. In this case, they must be declared public. When this entry point is introduced, the class name must also be included. If the class is not placed in the same package as the slice, it must also contain the package name.

L Other notifications can be introduced into the Pointcut by the method name

6.8 Priority of the specified slice

L when more than one facet is applied on the same connection point, their precedence is indeterminate unless explicitly specified.

the priority of the L-slice can be specified by implementing the Ordered interface or using @Order annotations.

L Implement the Ordered interface,the smaller the return value of theGetOrder () method, the higher the priority.

L If using @Order annotation, the serial number appears in the annotation

6.9 Note:

The

Above AOP is implemented by annotations, and AOP can actually be implemented in the same way as XML configuration!

<!--1. Configure the beans that need to be loaded into the IOC container--><bean id= "Logaspect" class= "Com.neuedu.aop.proxy.LogAspect" ></bean ><bean id= "Txaspect" class= "Com.neuedu.aop.target.TxAspect" ></bean><bean id= "Calculator" class= " Com.neuedu.aop.target.MathCalculatorImpl "></bean><!--2. To configure AOP, you need to import an AOP namespace--><aop:config> <!--declaration Pointcut expression--><aop:pointcut expression= "Execution (* com.neuedu.aop.target.mathcalculatorimpl.* (..))" id = "Mypointcut"/><!--Configure the Log slice class, reference the preceding class, control the priority through the Order property--><aop:aspect ref= logaspect "order=" ><!-- Specify the facet method of the slice class by using the method property, specifying the Pointcut expression by Pointcut-ref--><aop:before method= "Showbeginlog" pointcut-ref= "Mypointcut"/ ><aop:after method= "Showafterlog" pointcut-ref= "mypointcut"/><aop:after-throwing method= " Showexceptionlog "pointcut-ref=" Mypointcut "throwing=" ex "/><aop:after-returning method=" ShowReturnLog " pointcut-ref= "Mypointcut" returning= "result"/><aop:around method= "Around" pointcut-ref= "Mypointcut"/></aop:aspect><!--Configure the transaction plane class, referencing the preceding class--><aop:aspect ref= "Txaspect" order= "><aop:around method=" Around "pointcut-ref=" Mypointcut "/></aop:aspect></aop:config>

  

What you need to know is that the management of transactions is very much related to AOP, that is, the bottom of declarative transactions is implemented with transactions!

Spring frame--AOP (aspect-oriented programming) detailed

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.