First, the concept
AOP (Aspect oriented programming): Plane-oriented programming.
Aspect-oriented programming (also called facet-oriented programming) is a hotspot in software development and an important part of the spring framework. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.
Second, the use
Logging, performance statistics, security control, rights management, transaction processing, exception handling, resource pool management.
Third, detailed
Note: Please see the following blog post for your code.
1. Facets (Aspect)
The official abstraction is defined as "a focus of modularity, which may cross over multiple objects", in this case, "tangent" is the specific behavior of the class Testaspect, for example: Aserviceimpl.bara () Call is one of the behaviors that the tangent testaspect is concerned about. "Slices" are configured in the ApplicationContext <aop:aspect>.
2. Connection point (Joinpoint)
A behavior such as a call to Aserviceimpl.bara () or Bserviceimpl.barb (String _msg, int _type) that throws an exception during the execution of a program.
3. Notice (Advice)
The actions that "tangent" produces for a "connection point", for example, the action of logging the methods of all classes under the Com.spring.service package in Testaspect is a advice. Where a "slice" can contain multiple "Advice", such as Testaspect. There are 5 types of advice:
A pre-notification (before advice): A notification that is performed before a connection point (Joinpoint), but this notification does not prevent execution before the connection point. XML is declared using the <aop:before> element inside the <aop:aspect>, for example, the Dobefore method in Testaspect. The @before declaration is used in annotations, for example, the Dobefore method in Testannotationaspect.
B Post notification (after advice): Notification that is executed when a connection point exits (whether it is a normal return or an abnormal exit). The XML is declared using the <aop:after> element inside the <aop:aspect>. For example, the Doafter method in Testaspect, so the Doafter method is still executed when Bserviceimpl.barb throws an exception in Aoptest. The @after declaration is used in annotations.
C after return notification (after return advice): A notification that is executed after a connection point is completed normally, excluding the case where an exception was thrown. The XML is declared using the <after-returning> element inside the <aop:aspect>. Use @afterreturning declaration in annotations;
D Surround Notification (Around advice): A notification that surrounds a connection point, similar to the Dofilter method of the filter in the servlet specification in the Web. You can customize the behavior before and after the call to the method, or you can choose not to execute. The XML is declared using the <aop:around> element inside the <aop:aspect>. For example, the Doaround method in Testaspect. The @around declaration is used in annotations.
E-Notification After an exception is thrown (after throwing advice): Notification that is executed when the method throws an exception. The XML is declared using the <aop:after-throwing> element inside the <aop:aspect>. For example, the Dothrowing method in Testaspect. The @afterthrowing declaration is used in annotations.
Notification execution Order: pre-notification → surround notification connection point → connection point execution → surround notification connection point → return notification → post notification
→ (if an exception occurs) exception notification → after notification
4. Entry point (Pointcut)
An assertion that matches a connection point, a notification in AOP, and a Pointcut expression association. For example, all the notifications in Testaspect are concerned with connection points that are execution by pointcut expressions (* com.spring.service.*.* (..)) to decide.
Pointcut expression
execution: The connection point used to match the execution of the method;
within: Used to match method execution within a specified type;
this: used to match the execution method of the current AOP proxy object type, note that the type of the AOP proxy object matches, which may include the introduction of the interface as well as type matching; Note that the expression used in this must be the full class name, and wildcard characters are not supported;
Target: The execution method used to match the current target object type, note that the type of the target object matches, which does not include the introduction of the interface and type matching; Note that the expression used in target must be the full class name, and wildcard characters are not supported;
args: The method used to match the current execution of the passed parameter is the execution method of the specified type, the parameters in the parameter type list must be the full class name, the wildcard is not supported; args is a dynamic pointcut, which is very expensive and should not be used in non-special cases;
@within: Used to match so hold the method within the specified annotation type, and the annotation type must be the full class name;
@target: The execution method used to match the current target object type, where the target object holds the specified annotation, and the annotation type must be the full class name;
@args: The parameter that is used to match the current execution of the passed parameters holds the execution of the specified annotation, and the annotation type must be the full class name;
@annotation: Used to match the method in which the current execution method holds the specified annotation, and the annotation type must be the full class name;
Bean: Spring AOP Extended, ASPECTJ does not have a method of executing a Bean object that matches a particular name for an indicator;
reference Pointcut: Indicates references to other named pointcuts, only annotation style support, XML style not supported.
Match syntax
[Plain]View Plaincopy
- * Match any number of characters;
- .. Matches the repetition of any number of characters, such as matching any number of sub-packages in the type pattern, and matching any number of parameters in the method parameter pattern.
- + matches the subtype of the specified type; only the suffix can be placed behind the type pattern.
For example:
Java.lang.String match String type;
Java.*. String matches the string type under any one-level sub-package under the Java package, such as matching java.lang.String, but not matching java.lang.ss.String.
Java.. * matches any type of Java package and any sub-packages, such as matching java.lang.String, java.lang.annotation.Annotation.
Java.lang.*ing matches any type that ends with ing under any java.lang package;
java.lang.number+ matches the self-type of any number under the Java.lang package, such as matching Java.lang.Integer, which also matches Java.math.BigInteger.
Match type
Class A
[Plain]View Plaincopy
- Annotation class name
Annotations: Optional, annotations held on the class, such as @deprecated;
Class Name: Required, the full name of any class.
B method
[Plain]View Plaincopy
- Note Modifiers return value type class name Method name (parameter list) exception list
Annotations: Optional, Method-held annotations, such as @deprecated;
Modifiers: optional, such as public, protected;
Return value type: Required, can be any type mode; "*" denotes all types;
Class Name: Optional, full name of any class;
Method Name: Required, you can use "*" for pattern matching;
Parameter list: "()" means that the method does not have any parameters; "(..)" Indicates that a method that matches an arbitrary parameter is accepted, "(..., java.lang.String)" means that a match to the parameter that accepts the java.lang.String type ends, and that a method with any arguments can be accepted in front of it; "(Java.lang.String,..)" Represents a method that matches a parameter that accepts a java.lang.String type, and can accept any argument behind it; "(*,java.lang.string)" Represents a method that matches an argument that accepts a java.lang.String type and accepts an arbitrary type parameter in front of it;
Exception list: Optional, with "throws exception fully qualified Name list" declaration, the exception fully qualified name list if there are multiple "," split, such as throws Java.lang.IllegalArgumentException, Java.lang.ArrayIndexOutOfBoundsException.
C Bean
You can use the Bean's ID or name to match, and you can use the wildcard character "*".
Matching logical operations
can be used and (&&), or (| | ), Non-(! ) to combine pointcut expressions. The escape character "&&" is required to use "&&" in XML To replace it, so it is inconvenient, so spring ASP provides and, or, not to replace the &&, | |,!.
Pointcut Expression Example
A execution
Mode |
Describe |
Public * * (..) |
Execution of any public method |
* Cn.javass. Ipointcutservice.* () |
Any Cn.javass method in the Ipointcutservice interface under the packet and all sub-packages |
* Cn.javass. *.*(..) |
Cn.javass any method of any class under the package and all sub-packages |
* Cn.javass. ipointcutservice.* (*) |
Cn.javass Package and all sub-packages under Ipointcutservice interface any only one parameter method |
* (!cn.javass. ipointcutservice+). * (..) |
Any method that is not a "Cn.javass packet and all sub-packages Ipointcutservice interfaces and sub-types" |
* Cn.javass. Ipointcutservice+.* () |
Any Cn.javass method of Ipointcutservice interface and sub-type under the packet and all sub-packages |
* Cn.javass. ipointcut*.test* (Java.util.Date) |
Cn.javass Package and all sub-packages the Ipointcut prefix type is a method that starts with test with only one parameter type of java.util.Date, noting that the match is matched based on the parameter type of the method signature, not as defined by the type of argument passed in at execution time: public void Test (Object obj), which does not match even if it is passed into java.util.Date; |
* Cn.javass. ipointcut*.test* (..) throws IllegalArgumentException, arrayindexoutofboundsexception |
Cn.javass any method of Ipointcut prefix type under package and all sub-packages, and throws IllegalArgumentException and ArrayIndexOutOfBoundsException exceptions |
* (Cn.javass. ipointcutservice+&& java.io.serializable+). * (..) |
Any method that implements the type of Ipointcutservice interface and java.io.Serializable interface under the Cn.javass package and all sub-packages |
@java. lang.deprecated * * (..) |
Any method that holds @java.lang.deprecated annotations |
@java. lang.deprecated @cn. Javass. Secure * * (..) |
Any holding @java.lang.deprecated and @cn.javass. Methods for secure annotations |
@ (java.lang.Deprecated | | Cn.javass. Secure) * * (..) |
Any hold @java.lang.deprecated or @ cn.javass. Methods for secure annotations |
(@cn. Javass. Secure *) * (..) |
Any return value type holds @cn.javass. Secure method |
* (@cn. Javass. Secure *). * (..) |
Any type that defines the method holds @cn.javass. Secure method |
* * (@cn. Javass. Secure (*), @cn. Javass. Secure (*)) |
Any signature method with two parameters, and the two parameters are marked with @ Secure, such as public void Test (@Secure string str1, @Secure string str1); |
* * (@ cn.javass. Secure *) or * * (@ cn.javass). Secure *) |
Any method with one parameter, and the parameter type holds @ Cn.javass. Secure, such as public void test (model model), and @secure annotations on the model class |
* * (@cn. Javass. Secure (@cn. Javass. Secure *), @ cn.javass. Secure (@cn. Javass. Secure *)) |
Any method with two arguments, and both parameters are @ Cn.javass. Secure is marked, and the type of both parameters holds @ Cn.javass. Secure; |
* * (Java.util.map<cn.javass. Model, Cn.javass. Model>,..) |
Any method with a Java.util.Map parameter, and the parameter type is < cn.javass: Model, Cn.javass. Model > is a generic parameter; Note that only the first parameter is Java.util.Map, excluding subtypes, such as public void Test (Hashmap<model, model> Map, String str); You must use "* * * (java.util.hashmap<cn.javass. Model,cn.javass. Model>,..) " The public void test (map map, int i) will not match, because the generic parameter does not match |
* * (java.util.collection< @cn. Javass. Secure *>) |
Any method with one parameter (type java.util.Collection), and the parameter type is a generic parameter that holds @cn.javass on the generic parameter type: Secure annotations, such as public void Test (collection<model> Collection); The model type holds @cn.javass. Secure |
B within
Mode |
Describe |
Within (Cn.javass. *) |
Any method execution under Cn.javass package and sub-package |
Within (Cn.javass. ipointcutservice+) |
Cn.javass any method of Ipointcutservice type and subtype under a package or all sub-packages |
Within (@cn. Javass. Secure *) |
Hold Cn.javass. Any method of any type of secure annotation must be declared on the target object, which does not work on the interface. |
C this
Mode |
Describe |
This (Cn.javass.spring.chapter6.service.IPointcutService) |
The current AOP object implements any method of the Ipointcutservice interface |
This (Cn.javass.spring.chapter6.service.IIntroductionService) |
Any method by which the current AOP object implements the Iintroductionservice interface may also be an introduction interface |
D Target
Mode |
Describe |
Target (Cn.javass.spring.chapter6.service.IPointcutService) |
Any method that implements the Ipointcutservice interface for the current target object (non-AOP object) |
Target (Cn.javass.spring.chapter6.service.IIntroductionService) |
Any method that implements the Iintroductionservice interface for the current target object (non-AOP object) cannot be an ingestion interface |
Mode |
Describe |
Args (java.io.Serializable,..) |
Any one that starts with an "incoming parameter type of java.io.Serializable" and can follow a method of any of the arguments of any type, the parameter type specified by args is dynamically matched at run time. |
F @within
Mode |
Describe |
@within cn.javass.spring.chapter6.Secure) |
The type that corresponds to any target object holds the class method of the secure annotation; it must be declared on the target object, which does not work on the interface. |
G @target
Mode |
Describe |
@target (Cn.javass.spring.chapter6.Secure) |
Any target object that holds the class method for secure annotations must be declared on the target object, which does not work on the interface. |
H @args
Mode |
Describe |
@args (Cn.javass.spring.chapter6.Secure) |
Any one method that accepts only one parameter, and the arguments passed in when the method is run hold annotation cn.javass.spring.chapter6.Secure; a dynamic pointcut, similar to the ARG indicator; |
I @annotation
Mode |
Describe |
@annotation (Cn.javass.spring.chapter6.Secure) |
The current execution method holds annotations Cn.javass.spring.chapter6.Secure will be matched |
J Bean
Mode |
Describe |
Bean (*service) |
Match all beans that end with service naming (ID or name) |
K Reference Pointcut
[Java]View Plaincopy
- @Pointcut (value="Bean (*service)")
- Private void Pointcut1 () {}
- @Pointcut (value="@args (cn.javass.spring.chapter6.Secure)")
- Private void Pointcut2 () {}
- @Pointcut (value="POINTCUT1 () &&pointcut2 ()")
- Private void Pointcut3 () {}
Notification method Parameter Injection
In spring AOP, except that the execution and bean indicators cannot pass parameters to the notification method, other indicators can automatically pass matching parameters or objects to the notification method. For example:
[Java]View Plaincopy
- @Before (value="Execution (* Test (*)) && args (param)", argnames="param")
- Public void Before1 (String param) {
- System.out.println ("===param:" + param);
- }
First Execution (* TEST (*)) matches any method named Test, and has a parameter of any type;
Args (param) First looks for a parameter with the same name on the notification method, and when the method executes (at run time) the passed parameter is used with the same name as the parameter type, or java.lang.String, if the match will pass the notified parameter to the same name parameter on the notification method.
Other indicators (except execution and bean indicators) can be used in this way for parameter binding.
Comprehensive example
[Java]View Plaincopy
- @Before (value="args (param) && target (beans) && @annotation (Secure)", argnames="Jp,param,bean , secure ")
- Public void Before5 (joinpoint jp, String param,
- Ipointcutservice Pointcutservice, secure secure) {
- ......
- }
In addition to the common way described above, you can also get parameters automatically using named Pointcuts:
[Java]View Plaincopy
- @Pointcut (value="args (param)", argnames="param")
- Private void pointcut1 (String param) {}
- @Pointcut (value="@annotation (Secure)", argnames="secure")
- Private void Pointcut2 (Secure secure) {}
- @Before (value = "pointcut1 (param) && pointcut2 (Secure)", argnames="param, secure")
- Public void Before6 (joinpoint jp, String param, secure secure) {
- ......
- }
5. Target Object
An object that is notified by one or more facets. For example, Aservcieimpl and Bserviceimpl, of course, when actually running, Spring AOP takes the proxy implementation, the actual AOP operation is TargetObject proxy object.
6. AOP Agent (AOP proxy)
There are two kinds of proxy methods in spring AOP, JDK dynamic agent and cglib agent. By default, when the TargetObject implements the interface, the JDK dynamic agent is used, for example: Aserviceimpl; Conversely, Cglib proxy, for example: Bserviceimpl. Forcing the Cglib agent to use the Proxy-target-class property of <aop:config> is set to true.
Spring AOP Detailed Tutorial