Spring in Action -- AOP篇

1. What is aspect-oriented programming?

  • Concept: A technology that realizes the unified maintenance of program functions through pre-compilation and dynamic agents during runtime . The use of AOP can isolate the various parts of the business logic, thereby reducing the coupling between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development at the same time.

2. AOP terminology

2.1. Advice

  • In AOP terminology, aspect work is called notification,
  • 5 types of notifications can be applied to Spring aspects
    • Before notification (Before): use the notification function before the target method is called
    • After notification (After): The notification is called after the target method is completed, and you don't care about the output of the method at this time.
    • After-returning: After the target method is successfully executed, the notification is called
    • After-throwing: The notification is called after the target method throws an exception.
    • Aroud: The notification wraps the notified method, and performs custom behavior before and after the notified method is called.

2.2, cut point

  • If the notification defines the “what” and “when” of the aspect, then the point of cut defines the “where”, and the definition of the point of cut will match the multiple connection points that the notification will be woven into. We usually use explicit class and method names, or use regular expressions to define matching class and method names to specify these pointcuts.

2.3. Connection point

  • A connection point is a point that can be inserted into the aspect during application execution. Our app also has thousands of timing app notifications,
  • This point can be when a method is called, when an exception is thrown, or even when a field is modified. The aspect code can use these points to insert into the normal flow of the application and add new behaviors.

2.4, section

  • The aspect is the combination of notice and point. The notification and pointcut together define the entire content of the aspect—what it is, where and where it fulfills its function.

3. Spring's support for AOP

3.1. Concept

  • It is the basic function of the AOP framework to create pointcuts to define the connection points where the aspect lock is woven.

3.2. Spring provides 4 types of AOP support

  • Classic Spring AOP based on proxy (cumbersome and too complicated, basically deprecated)
  • Pure POJO aspect (need to configure XML)
  • @AspectJ annotation-driven aspect (based on annotations)
  • Injected AspectJ aspects (applicable to all versions of Spring)
  • The first three are the issues of Spring AOP implementation. Spring AOP is built on the basis of dynamic proxy. Therefore, Spring's support for AOP is limited to method interception.

3.3, Spring notifies the object at runtime

  • Spring weaves the aspects into Spring-managed Beans during runtime, wraps the aspects and encapsulates the target class in the proxy class, intercepts the call of the notified method, and then forwards the call to the real target bean.
  • When the proxy intercepts the method call, before calling the target bean to send the method, it will execute the aspect logic
    Insert picture description here
  • Spring creates proxy objects only when the application needs a bean to be proxied, so we don't need a special compiler to weave the aspects of Spring AOP.

3.4, Spring only supports method-level connection points

  • Because Spring is based on dynamic proxy, Spring only supports method connection points.
  • AspectJ and JBoss, in addition to method pointcuts, they also provide field and constructor access points.
  • Spring lacks support for field connection points, and cannot allow us to create fine-grained notifications, such as intercepting the modification of object fields.

4. Select the connection point through the cut point

  • The cut point is used to accurately locate the notification of the aspect in which store should be used. The notification and its order are the most basic elements of the aspect.
    Insert picture description here
  • Note that only the execution indicator is actually executed to match, and other indicators are used to limit the match.

4.1, write cut points

  • We need to have a theme to define the cut point of the aspect, so define a Performance interface
package concert;

public interface Prformance{
    
    
	public void perform();
}
  • Pointcut expression, this expression agency can set the call to trigger notification when the perform() method is executed.
    Insert picture description here
  • Assume that the pointcut we need to match only matches the concert package. You can use the within() indicator to limit matching.
  • && stands for and, || stands for or,! Represents not, and special characters in xml have special meanings, so we still use and in xml
    Insert picture description here

4.2, select bean in the cut point

  • Spring also introduced a new bean() indicator, which allows us to use the bean ID in its single expression to identify the bean.
  • We want to apply the notification when the target method is executed, but limit the bean ID to woodstock.
    Insert picture description here
    Insert picture description here

5. Use annotations to create aspects

5.1, define the aspect

  • The annotation-oriented model of AspectJ can easily convert any class into an aspect with a small amount of annotations.
    Insert picture description here
  • Annotation is used here to declare the notification method, and the target method of the cut point is indicated in the notification annotation
  • AspectJ provides five annotations to define notifications.
    Insert picture description here
  • It can be seen that in the above aspect, we define a pointcut expression for each annotation as its value, and sometimes it is repeated, then we can use the @Pointcut annotation to define a reusable pointcut in an AspectJ aspect,
    Insert picture description here
  • Note here that although @AspectJ is used to indicate an aspect, it is still a POJO. We can call its methods like other classes, perform unit tests, and can also be assembled as a bean in Spring
    Insert picture description here
  • If it is only defined as a bean in the Spring container, even if the class is annotated with @AspectJ annotation, it will not be regarded as an aspect, these annotations will not be parsed, and no proxy will be created to convert it into an aspect.
  • We need to enable the automatic proxy function through the annotation @EnableAspectJ-AutoProxy on the configuration class.
    Insert picture description here
  • If you want to use XML to assemble beans in Spring, you need to use the <aop:aspectj-autoproxy> element in the Spring aop namespace.
    Insert picture description here
  • In this way, whether you use JavaConfig or XML, the AspectJ automatic proxy will encounter a proxy for the bean annotated with @AspectJ, and this proxy will surround all the beans that match the pointcut of the aspect.

5.2. Create surround notifications.

  • Surrounding solutes are the most powerful notification type.
  • It enables the logic you write to completely wrap the target method that is notified.
    Insert picture description here
  • The @Aroud annotation indicates that the watchPerformance() method returns to the surround notification of the performance() cutpoint.
  • It must accept ProceedingJoinPoint as a parameter. When the notified method is called through it in the notification, it needs to call the proceed() method. If it is not mobilized, it may block the call of the notified method.

5.3. Process the parameters in the notification.

Insert picture description here

  • The @pointcut annotation is used to define named pointcuts as before, but the difference is that the parameters to be provided to the notification method are declared at the pointcut.
    Insert picture description here
  • Note the args(trackNumber) qualifier, which indicates that the int type parameter passed to the playTrack() method will also be passed to the notification.
  • The parameters in the pointcut definition are the same as the parameter names in the pointcut method, which completes the transfer of parameters from the named pointcut to the notification method.
  • Method packaging is only one of the functions that can be achieved by the aspect.

5.4. Introduce new functions through annotations.

  • Using the AOP concept known as the introduction, aspects can add new methods to Spring beans.
    Insert picture description here
  • When the method of the introduced interface is called, the agent delegates the call to other objects that implement the new interface. In fact, the implementation of a bean is split into multiple classes.
  • Verification, the introduction of an Encoreable interface.
    Insert picture description here
  • Create a new aspect. No notifications such as front, rear, or surround are provided. Instead, the Encoreable interface is introduced into the Perormance bean through the @DeclareParents annotation.
    Insert picture description here
    Insert picture description here
  • Note that we need to declare EncoreableIntroducer as a bean in the Spring application
<bean class = "concert.EncoreableIntroducer">
  • Spring's automatic proxy mechanism will get its declaration. When Spring finds that a bean uses the @Aspect annotation, Spring will create a proxy, and then call the delegated bean or the introduced implementation, depending on Whether the method called belongs to the bean being proxied or the interface being introduced.

6. Declare aspects in XML.

  • The annotation-based configuration should be based on the java-based configuration, and the java-based configuration should be due to the XML-based configuration. If you want to declare the aspect, but cannot add annotations to the notification class, you must use the XML configuration.
    Insert picture description here
    Insert picture description here
  • Remove all annotations from the previous class
    Insert picture description here

6.1. Pre-declaration and post-notification

Insert picture description here

  • Most AOP configuration elements must be used within <aop:config>the context of the element. There are several exceptions to this rule, but when the bean is declared as an aspect, we always <aop:config>configure it from the beginning.
  • Within this element, we can declare one or more notifications, aspects or points of contact.
  • Use the method attribute declaration method in the notification annotation (<aop:before>), and use the pointcut to declare the pointcut.

Insert picture description here

  • In all notification elements, the pointcut attribute defines the pointcut applied by the notification, and its value is the pointcut defined by the AspectJ pointcut expression syntax.
  • Use <aop:pointcut>definitions to name common pointcuts
    Insert picture description here

6.2. The statement surrounds the notice.

  • Restore the watjcPerformance() method.
    Insert picture description here
  • Use <aop:around>elements to declare surrounding notifications in XML.
    Insert picture description here

6.3. Pass parameters for notification.

  • Similarly, remove all @AspectJ annotations on TrackCounter before.
    Insert picture description here
  • Use XML to configure TrackCounter as a parameterized aspect.
    Insert picture description here

6.4. Introduce new features through aspects

  • In the previous section, we introduced new methods for the notified method with the help of Aspect's @DeclareParents annotation. We can also use <aop:declare-parents>elements in XML .
    Insert picture description here
  • Those beans whose types match the Performance interface (specified by the types-matching attribute) will have an Enableable interface (specified by the implement-interface attribute) added to the parent class structure.
  • We use the fully qualified class name of the default-impl attribute to show the implementation of the specified Encoreable. Or use the delegate-ref attribute to identify.
    Insert picture description here
  • Here is a reference to a bean, so we have to create a bean. The difference between using default-impl to identify the world and indirectly using delegate-ref is that the latter is a Spring bean, which itself can be injected, notified, or use other Spring configurations.
    Insert picture description here

7. Summary

  • Function: The use of AOP can isolate various parts of the business logic, thereby reducing the coupling between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development at the same time.
  • Use: You can use AOP in the form of annotations or XML writing.

Guess you like

Origin blog.csdn.net/JISOOLUO/article/details/105707380