As we all know, spring's core two functions are AOP and IOC, that is, face-tangent, control inversion. Here we discuss how to use spring AOP.
1. What is AOP
AOP full name aspect oriented programming, aspect-oriented, AOP is mainly implemented in order to extract the facets in the process of business processing, it is faced with a process of a step or stage, in order to obtain the logic process between the parts of the isolation effect of low coupling. It is similar to the task of the design pattern, is to provide another angle to think about the structure of the program, to compensate for the lack of object-oriented programming.
The popular point is to provide a mechanism for providing slice injection for a business implementation, in which the defined facets are bound to the business through pointcuts in order to enable the binding of some special logic into the business.
For example, if a logging function is needed, the first thing to think about is logging through log4j or other frameworks in the method, but writing down to find a problem, the core business code is not much in the whole business, it is some log or other auxiliary code. And many businesses need the same functionality, such as the need to log, it is necessary to copy the functions of these logging, even if it is packaged into a framework, but also need to call. Using complex design patterns here is not worth the candle.
So we have to face the plane.
3. Building AOP
Originally, Spring came with a set of AOP implementations, and we used this implementation directly, and some XML files would have to be defined using AOP, but this step was omitted because we were using the Spring-boot framework. In other words, in spring-boot, we can use AOP directly without any configuration
Concrete how to build Spring-boot please refer to: http://www.cnblogs.com/lic309/p/4073307.html
4.AOP Name
First introduce some of the AOP nouns, in fact, these nouns have no effect on the use of AOP, but in order to better understand the best to know some
Facets (Aspect): A focus of modularity, which may be crosscutting across multiple objects. Transaction management is a good example of a crosscutting concern in the Java EE application. In spring AOP, facets can be implemented using patterns-based or @aspect annotations.
connection point (Joinpoint): a particular point in the execution of a program, such as when a method is called or when an exception is handled. In spring AOP, a connection point always represents the execution of a method.
notification (Advice): An action performed on a particular connection point on a slice. These include different types of notifications such as "Around", "before", and "after" (the type of notification will be discussed later). Many of the AOP frameworks, including spring, are notification models with interceptors , and maintain an interceptor chain centered on the connection point.
pointcut (Pointcut): An assertion that matches a connection point. The notification is associated with a pointcut expression and runs on the connection point that satisfies the pointcut (for example, when a method for a particular name is executed). How Pointcut expressions match connection points is the core of AOP: Spring defaults to using the ASPECTJ pointcut syntax.
introduced (Introduction): Used to declare additional methods or properties for a type (also known as a connection type declaration (Inter-type declaration)). Spring allows the introduction of new interfaces (and a corresponding implementation) to any Proxied object. For example, you can use ingestion to enable a bean to implement the ismodified interface to simplify the caching mechanism.
target Object: An object that is notified by one or more facets. Also called made informed (advised) objects. Since spring AOP is implemented by the runtime proxy, this object is always a proxy (proxied) object.
AOP Proxy: An object created by the AOP framework to implement a facet contract (such as notification method execution, and so on). In spring, an AOP proxy can be either a JDK dynamic agent or a cglib proxy.
Weaving (Weaving): Connects the facets to other application types or objects, and creates a notified object. These can be done at compile time (for example, with the AspectJ compiler), at class load time, and at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time.
Some of the important nouns are: facets, entry points
5. Simple example:
May be directly said will be very vague, here I first made a small example: directly on the code
//describe the Slice class@Aspect @configuration Public classTESTAOP {/** Define a pointcut*/ //@Pointcut ("Execution (* findbyid* (..))")@Pointcut ("Execution (* com.test.service.cachedemoservice.find* (..))") Public voidExcudeservice () {}/** Cut through the connection point*/@Before ("Execution (* findbyid* (..)) && "+" args (id,..) ") Public voidtwiceAsOld1 (Long id) {SYSTEM.ERR.PRINTLN ("Slice before performed .... id== "+ID); } @Around ("Excudeservice ()") PublicObject twiceasold (proceedingjoinpoint thisjoinpoint) {System.err.println ("The slice has executed .... "); Try{Thing Thing=(Thing) thisjoinpoint.proceed (); Thing.setname (Thing.getname ()+ "========="); returnthing; } Catch(Throwable e) {e.printstacktrace (); } return NULL; }}
Look at the example above is the realization of a slice, which has some special things, the following one by one explanation:
6. Annotations used:
@Aspect: Describes a slice class that needs to be annotated when defining a slice class
@Configuration: Spring-boot Configuration Class
1. @Pointcut: Declare a pointcut that determines what the connection points are interested in, allowing us to control when notifications are executed. Spring AOP supports only spring bean methods for executing connection points . So you can think of the pointcut as a match for the method execution on the spring bean. A pointcut declaration has two parts: a signature that contains the name and any arguments, and a pointcut expression that determines the execution of the method that we care about.
Note: A method that is signed as a pointcut must return a void type
Spring AOP supports the use of pointcut indicators in pointcut expressions such as the following:
Execution -Match method execution of the connection point, which is the most important pointcut indicator you will use for spring.
within -Qualify matching connection points of a particular type (execution of methods defined in the matching type when using Spring AOP).
This -Qualifying matches to a specific connection point (execution of the method using Spring AOP), where bean reference (Spring AOP proxy) is an instance of the specified type.
Target -Qualifying matches to a specific connection point (execution of the method using Spring AOP), where the target object (the applied object being proxied) is an instance of the specified type.
args -Qualifying matches to a specific connection point (execution of the method using Spring AOP), where the parameter is an instance of the specified type.
@target -Qualifying matches to a specific connection point (execution of the method using Spring AOP), where the class that is executing the object holds annotations of the specified type.
@args -Qualifying matches to a specific connection point (execution of the method using Spring AOP), where the run-time type of the actual incoming parameter holds annotations of the specified type.
@within -limits the match to a specific connection point where the type of the connection point has a specified annotation (when using spring AOP, the type of the method being executed has the annotation specified).
@annotation -Qualifying matches to a specific connection point (execution of the method using Spring AOP), where the topic of the connection point holds the specified annotation.
Where execution is used most frequently, that is, when a method executes, it is cut. There is an important knowledge in defining pointcuts, namely pointcut expressions, in which we will explain how to write pointcut expressions.
Pointcut means when to cut into what method, defining a pointcut is equivalent to defining a "variable", the specific time to use this variable requires a notification.
Joins the tangent plane to the target object .
As shown in the example, notifications can be defined by annotations, and the parameters in the annotations are pointcuts.
Notifications supported by Spring AOP:
@Before: Forward notification: A notification that is executed before a connection point, but this notification does not block the execution process before the connection point (unless it throws an exception).
@AfterReturning : Post notification: A notification that executes after a connection point is completed normally, usually when a matching method returns.
You can bind the return value in a post-notification, such as:
@AfterReturning ( pointcut=com.test.service.cachedemoservice.findbyid (..)) ", returning=" RetVal ") publicvoid Dofindbyidcheck (Object retVal) { // ... }
@AfterThrowing: Exception notification: A notification that is executed when a method throws an exception exits.
@After Final Notice. the notification that is executed when a connection point exits (whether it is a normal return or an abnormal exit).
@Around: Surround Notification: A notification that surrounds a connection point, such as a method call. This is the most powerful type of notification. Surround notifications can accomplish custom behavior before and after a method call. It also chooses whether to continue execution of the connection point or to return its own return value directly or throw an exception to end the execution.
Surround notification is the most troublesome, but also the most powerful, it is a method of the wrapping, the specific method will be passed through the agent to the plane, the plane can choose to execute the method or not, the execution method several times.
Surround notification uses an object of the proxy proceedingjoinpoint type to manage the target object, so the first parameter of this notification must be the proceedingjoinpoint type, in the notification body, called Proceedingjoinpoint 's Proceed () method causes the connection point method in the background to execute. Proceed method may also be called and passed in a object[] Object-The value in the array will be used as a parameter when the method executes.
7. Notification Parameters
Any notification method can define the first parameter as the org.aspectj.lang.JoinPoint type (wrapping notification needs to define the first argument as the proceedingjoinpoint type, which is a subclass of Joinpoint). The joinpoint interface provides a number of useful methods, such as Getargs ()(return method parameters),getthis ()(return proxy object),Gettarget () (return to target),getsignature ()(returns information about the method being notified) and toString ()(useful information to print out the method being notified)
Sometimes when we define a slice, we need to use a parameter to the target object in the slice, how to make the tangent to get the target object's parameters.
A method can be seen from the example:
Use args to bind. If a parameter name is used where the type name should be used in an args expression, the corresponding parameter value will be passed in when the notification is executed.
@Before ("Execution (* findbyid* (..)) && "+" args (id,..) " Publicvoid twiceAsOld1 (Long id) { System.err.println ("tangent before executed ...." ) id== "+ ID); }
@Around ("Execution (list<account> find* (. )) && "+ " Com.xyz.myapp.SystemArchitecture.inDataAccessLayer () && "+ " Args (Accountholdernamepattern) ") public Object Preprocessquerypattern (Proceedingjoinpoint PJP, String accountholdernamepattern)throws throwable { = preprocess (accountholdernamepattern); return pjp.proceed (new object[] {newpattern});}
8. Pointcut expression
Now let's introduce the most important pointcut expressions:
As mentioned above, defining a pointcut requires a signature with a name and any arguments, and a pointcut expression, which is * findbyid* (..) this part.
Format of pointcut expression:execution ([visibility] return type [claim type]. Method name (parameter) [exception])
Where "" is optional, the others also support the use of wildcards:
*: Match all characters
.. : Typically used to match multiple packages, multiple parameters
+: Represents a class and its subclasses
Operators are:&&, | |,!
Pointcut expression Keywords:
1) Execution: used to match sub-expressions.
Matches all methods in all classes in the Com.cjm.model package and its child packages, returns the type arbitrarily, and any of the method parameters
@Pointcut ("Execution (* Com.cjm.model). *.*(..))")
public void before () {}
2) Within: Used to match the Java class or package where the connection point resides.
Match all methods in the person class
@Pointcut ("Within (Com.cjm.model.Person)")
public void before () {}
Match all methods in all classes in the COM.CJM package and its child packages
@Pointcut ("Within (COM.CJM. *)")
public void before () {}
3) This: the reference used to pass in the proxy object to the notification method.
@Before ("before () && this (proxy)")
public void Beforeadvide (Joinpoint point, Object proxy) {
Processing logic
}
4) Target: The reference used to pass in the target object to the notification method.
@Before ("before () && target (target)
public void Beforeadvide (Joinpoint point, Object proxy) {
Processing logic
}
5) args: Used to pass parameters to the notification method.
@Before ("before () && args (age,username)")
public void Beforeadvide (joinpoint, int, String username) {
Processing logic
}
6) @within : The class used to match annotations that are determined using the parameter at the class level, all of its methods will be matched.
@Pointcut ("@within (com.cjm.annotation.AdviceAnnotation)")-all classes labeled by @adviceannotation will match
public void before () {}
7) @target : Similar to @within, but the retention policy of the annotation interface must be specified as runtime.
@Pointcut ("@target (com.cjm.annotation.AdviceAnnotation)")
public void before () {}
8) @args : The Java class for the object that is passed into the connection point must be annotated with the annotation annotation specified by @args.
@Before ("@args (com.cjm.annotation.AdviceAnnotation)")
public void Beforeadvide (Joinpoint point) {
Processing logic
}
9) @annotation : The method that matches the annotation annotation specified by its parameters by the connection point. That is, all methods that are annotated with the specified annotation will match.
@Pointcut ("@annotation (com.cjm.annotation.AdviceAnnotation)")
public void before () {}
Bean: The bean in which the connection point resides is qualified by the name of the managed bean. This keyword is Spring2.5 new.
@Pointcut ("Bean (person)")
public void before () {}
9. References
http://blog.csdn.net/yuqinying112/article/details/7244281
Http://www.2cto.com/kf/201204/128280.html
http://blog.csdn.net/archie2010/article/details/6254343
"Spring-boot" Spring AOP First contact for tangent plane programming