[Spring-boot] spring aop is initially exposed to aspect programming, spring-bootaop

Source: Internet
Author: User

[Spring-boot] spring aop is initially exposed to aspect programming, spring-bootaop

As we all know, spring has two core functions: aop and ioc, that is, face-oriented and control inversion. Here we will discuss how to use spring aop.

1. What is aop?

The full name of aop is Aspect Oriented Programming, which is Oriented to the Aspect. The main purpose of AOP is to extract the Aspect of the business processing process. It is faced with a certain step or stage in the processing process, in order to obtain the isolation effect of low coupling between different parts in the logical process. Similar to the task completed by the design pattern, it provides another way of thinking about the program structure to make up for the shortcomings of object-oriented programming.

In layman's terms, we provide a plane injection mechanism for a business implementation. In this way, the defined plane is bound to the business by the starting point during business operation, to bind some special logic to this service.

For example, if you need a logging function, you first think of Logging through log4j or other frameworks in the method, but writing it down to find a problem, in fact, the core business code is not much in the entire business. It is some logs or other auxiliary code. In addition, many businesses need the same functions, such as logging. At this time, we need to copy these logging functions. Even if they are encapsulated into a framework, they also need to be called. The use of complex design patterns here is not worth the candle.

So we need to face the aspect.

3. Set up aop

Spring has a built-in set of aop implementation. We can use this implementation directly. We still need to define some xml files to use aop, but because we use the spring-boot framework, this step is omitted. That is to say, in spring-boot, we can directly use aop without any configuration.

For more information about how to build spring-boot, see: http://www.cnblogs.com/lic309/p/4073307.html

4. aop name

First, I would like to introduce some aop terms. In fact, these terms have no impact on the use of aop, but I 'd better know some of them for a better understanding.

  • Aspect (Aspect): Modularization of a focus, which may cross multiple objects. Transaction Management is a good example of cross-cutting concerns in J2EE applications. In Spring AOP, the Aspect can be implemented by using the mode or @ Aspect annotation.

  • Join point (Joinpoint): A specific point in the program execution process, such as when a method is called or when an exception is handled. In Spring AOP, a connection pointAlwaysIndicates the execution of a method.

  • Advice): The action performed on a specific connection point of a plane. This includes different types of notifications, such as "around", "before", and "after" (the types of notifications will be discussed later ). Many AOP frameworks (including Spring) UseInterceptorCreate a notification model and maintain an interceptor chain centered on the connection point.

  • Pointcut): Assertion that matches the connection point. A notification is associated with an entry expression and runs on the connection point that meets the entry expression (for example, when a method with a specific name is executed ). How the entry point expression matches the connection point is the core of AOP: Spring uses the AspectJ entry point syntax by default.

  • Introduction (Introduction): Used to declare additional methods or attributes for a type (also known as the connection type declaration (inter-type declaration )). Spring allows the introduction of new interfaces (and a corresponding implementation) to any proxy object. For example, you can use introduction to implement a bean.IsModifiedInterface to simplify the cache mechanism.

  • Target Object): The object to be notified by one or more slices. Also calledAdvised)Object. Since Spring AOP is implemented in the runtime era, this object will always beProxied)Object.

  • AOP Proxy): The object created by the AOP framework, used to implement the section contract (for example, the notification method execution ). In Spring, the AOP proxy can be JDK dynamic proxy or CGLIB proxy.

  • Weaving): Connect a plane to another application type or object and create a notification object. These can be completed at compilation (for example, using the AspectJ compiler), class loading and runtime. Like other pure Java AOP frameworks, Spring completes weaving at runtime.

Important terms include: cut surface and entry point

5. Simple Example:

It may be very vague. Here I made a small example: directly add the code

    

// Description cut-in class @ Aspect @ Configurationpublic class TestAop {/** defines a starting point * // @ Pointcut ("execution (* findById *(..)) ") @ Pointcut (" execution (* com. test. service. cacheDemoService. find *(..)) ") public void excudeService () {}/ ** use the connection point to cut in */@ Before (" execution (* findById *(..)) & "+" args (id ,..) ") public void twiceAsOld1 (Long id) {System. err. println ("aspect before executed .... Id = "+ id) ;}@ Around (" excudeService () ") public Object twiceAsOld (ProceedingJoinPoint thisJoinPoint) {System. err. println (" aspect is executed .... "); Try {Thing thing = (Thing) thisJoinPoint. proceed (); thing. setName (thing. getName () + "=========="); return thing;} catch (Throwable e) {e. printStackTrace ();} return null ;}}

The above example shows how to implement a plane. There are some special things, which are explained as follows:

6. Annotations used:

@ Aspect: Describe a partition class. This annotation is required when defining the partition class.

@ Configuration: spring-boot Configuration class

1. @ Pointcut: declares an entry point. The entry point determines the content of the connection point, so that we can control when the notification will be executed.Spring AOP only supports Spring bean method execution connection points. So you can regard the starting point as a matching method execution on Spring bean. A Checkpoint Declaration has two parts: a signature containing the name and any parameters, and a checkpoint expression, which determines that we are concerned about the execution of the method.

Note: The method used as the entry point signature must be returned.VoidType

Spring AOP supports using the following entry point indicator in the entry point expression:

    • Execution-The connection point for matching method execution. This is the main entry point indicator of Spring that you will use.

    • Within-Restrict the connection points that match a specific type (execute the methods defined in the matching type when using Spring AOP ).

    • This-Restrict matching of specific connection points (execution of methods when Spring AOP is used). bean reference (Spring AOP proxy) is an instance of the specified type.

    • Target-Restrict matching of specific connection points (execution of methods when Spring AOP is used). The target object (the application object to be proxies) is an instance of the specified type.

    • Args-Restrict matching of specific connection points (execution of methods when Spring AOP is used). The parameter is an instance of the specified type.

    • @ Target-Restrict matching of specific connection points (method execution when Spring AOP is used). The class of the positive execution object holds the annotation of the specified type.

    • @ Args-Restrict matching of specific connection points (execution of methods when Spring AOP is used). The actual runtime type of input parameters holds the annotation of the specified type.

    • @-Restrict matching of specific connection points, where the type of the connection point has been specified for annotation (when Spring AOP is used, the type of the method executed has been specified for annotation ).

    • @ Annotation-Restrict matching of specific connection points (execution of methods when Spring AOP is used). The topic of the connection point holds the specified annotation.

WhereExecutionMost frequently used, that is, when a method is executed. There is an important knowledge in defining the entry point, that is, the entry point expression. We will explain how to write the entry point expression later.

The starting point means when to cut in the method. Defining a starting point is equivalent to defining a "variable". A notification is required when to use this variable.

Face to face andTarget objectConnect.

As shown in the example, notifications can be defined through annotations, and parameters in annotations are the entry points.

Notifications supported by spring aop:

@ Before: pre-notification: Notification executed Before a connection point, but this notification cannot prevent the execution process Before the connection point (unless it throws an exception ).

  @ AfterReturning: Post-Notification: the notification that is executed after a connection point is normally completed, usually executed when a matching method returns.

You can bind the return value to the post-notification, for example:

@AfterReturning(    pointcut=com.test.service.CacheDemoService.findById(..))",    returning="retVal")  public void doFindByIdCheck(Object retVal) {    // ...  }

@ AfterThrowing: exception notification: the notification executed when the method throws an exception and exits.

@ After: The final notification. The notification that is executed when a connection point exits (whether it is normal return or abnormal exit ).

@ Around:Surround notification: notifications that enclose a connection point, such as method calls. This is the most powerful notification type. Surround notifications can complete custom actions before and after method calls. It will also choose whether to continue executing the connection point or directly return its own return value or throw an exception to end the execution.

      Surround notification is the most troublesome and powerful. It is a method that is passed to the plane through a proxy. You can select whether to execute the method or not in the plane and how many times to execute the method.

Use a proxy for surround notificationsProceedingJoinPointObject Type to manage the target object, so the first parameter of this notification must beProceedingJoinPointType, called in the notification bodyProceedingJoinPointOfProceed ()Method will cause the connection point method to be executed in the background.ProceedMethod may also be called andObject []Object-the value in the array will be used as a parameter for method execution.

7. Notification Parameters

Any notification method can define the first parameterOrg. aspectj. lang. JoinPointType (the first parameter of the surround notification must be definedProceedingJoinPointType, which isJoinPoint).JoinPointInterfaces provide a series of useful methods, suchGetArgs ()(Return method parameters ),GetThis ()(Return proxy object ),GetTarget ()(Return target ),GetSignature ()(Return information about the method being notified) andToString ()(Print out useful information about the method being notified)

Sometimes, when defining a plane, we need to use a parameter of the target object in the plane. How can we make the plane get the parameter of the target object.

From the example, we can see a method:

UseArgs. If a parameter name should be used in an args expression where the type name is used, the corresponding parameter value will be passed in when the notification is executed.

  

@ Before ("execution (* findById *(..)) & "+" args (id ,..) ") public void twiceAsOld1 (Long id) {System. err. println ("aspect 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 {  String newPattern = preProcess(accountHolderNamePattern);  return pjp.proceed(new Object[] {newPattern});}        

 

8. Entry Point expression

Now we will introduce the most important entry point expressions:

As mentioned above, a signature containing the name and any parameters is required when defining the entry point, and a new entry expression is * findById.

Format of the entry expression: execution ([visibility] return type [Declaration type]. Method Name (parameter) [Exception])

Optional in []. Other Wildcards are also supported:

*: Match all characters
...: It is generally used to match multiple packages and multiple parameters.
+: Indicates the class and its subclass.

Operators include: &, |, and ,!

  

Entry Point expression keywords:

1) execution: Used to match a subexpression.

// Match all the methods in the com. cjm. model package and all the classes in its sub-packages. the return value is of any type and the method parameter is of any type.
@ Pointcut ("execution (* com. cjm. model ..*.*(..))")
Public void before (){}

 

2) within: Used to match the Java class or package where the connection point is located.

// 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 sub-Package

@ Pointcut ("within (com. cjm ..*)")
Public void before (){}

 

3) this: Used to reference the proxy object in the notification method.
@ Before ("before () & this (proxy )")
Public void beforeAdvide (JoinPoint point, Object proxy ){
// Processing logic
}

 

4) target: Used to reference the target object in 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 point, int age, String username ){
// Processing logic
}
 
6) @ within: it is used to match the class that uses the annotation specified by the parameter at the class level, and all its methods will be matched.

@ Pointcut ("@ within (com. cjm. annotation. AdviceAnnotation)")-All classes marked by @ AdviceAnnotation will match
Public void before (){}

  

7) @ target: the function of @ within is similar to that of @ 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 corresponding to the object passing in the connection point must be annotated with the Annotation specified by @ args.
@ Before ("@ args (com. cjm. annotation. AdviceAnnotation )")
Public void beforeAdvide (JoinPoint point ){
// Processing logic
}

  

9) @ annotation: method that matches the Annotation annotation specified by its parameter at the connection point. That is to say, all the methods marked by the specified annotation will match.
@ Pointcut ("@ annotation (com. cjm. annotation. AdviceAnnotation )")
Public void before (){}

10) bean: Specify the Bean where the connection point is located by the name of the managed Bean. This keyword is added to Spring2.5.
@ 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

    

    

 


What aspects does spring's AOP aspect programming use in actual projects? How many examples are there?

Hibernate transaction control
Log Management for large systems...
Many aspects that require cross-section programming can be used.
Reduces the number of duplicate codes and increases programming efficiency

How does Spring use AOP for aspect-oriented, something at the bottom of spring?

.. Mode .. Dynamic proxy
 

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.