Take a brief look at Spring AOP

Spring AOP topic

What is AOP

AOP (Aspect Oriented Programming) means aspect-oriented programming, a technology that realizes the unified maintenance of program functions by pre-compiling and running dynamic agents. (See my previous blog for dynamic agents). Hereafter, AOP is called "crosscutting".
The "cross-cutting" technology dissected the inside of the encapsulated object, and encapsulated the common behaviors that affect multiple classes into a reusable module, and named it "Aspect", that is, the aspect. The so-called "aspects" are simply those logic or responsibilities that have nothing to do with the business, but are called by business modules, which are encapsulated, which is convenient to reduce the repetitive code of the system, reduce the coupling between modules, and facilitate future operability And maintainability. Using "cross-cutting" technology, AOР divides the software system into two parts: core concerns and cross-cutting concerns. The main process of business processing is the core concern, and the less relevant part is the crosscutting concern. A characteristic of crosscutting concerns is that they often occur in multiple places of the core concern, and they are basically similar everywhere, such as permission authentication, logs, and things. The role of AOP is to separate the various concerns in the system and separate the core concerns from the cross-cutting concerns.

To sum up, the core idea of ​​AOP is one sentence:

Do not add new functions by modifying the source code.

AOP application scenarios

So what are the application scenarios of AOP in actual development?

1. Authentication permissions

2. Caching cache

3. Context passing content delivery

4. Error handling

5. Lazy loading

6. Debugging

7, logging, tracing, profiling and monitoring record tracking optimization calibration

8, Persistence persistence

8. Performance optimization

10. Resource pooling

11.Synchronization

12. Transactions

The role of AOP in Spring

Provides declarative transactions; allows users to customize aspects

The core concept of AOP

  • Cross-cutting concerns: methods or functions that span multiple modules of an application. Even if it is not related to our business logic, the part we need to focus on is the cross-cutting focus. Such as: log, security, cache, transaction, etc...…
  • ASPECT: A special object whose cross-cutting concerns are modularized. That is, it is a class.

It can be simply considered that a class annotated with @Aspect is an aspect.

  • Advice: The so-called notification is the code to be executed after intercepting the connection point. The notification is divided into five categories: pre-, post-, exception, final, and surround notification.
Notification type Junction Implement interface
Before advice (before advice) Before the method org.springframework.aop.MethodBeforeAdvice
Post notification() After the method org.springframework.aop.AfterReturningAdvice
Surround notification() Before and after the method org.aopalliance.intercept.MethodInterceptor
Exception throw notification() Method throws an exception org.springframework.aop.ThrowsAdvice
Referral notice() Add new method attributes to the class org.springframework.aop.IntroductionInterceptor
  • Target: The object to be notified.
  • Proxy: The object created after applying the notification to the target object.
  • PointCut: The definition of the "location" of the point cut notification execution.
  • Joint Point (JointPoint): the execution point that matches the entry point.

Thoroughly understand aspect, join point, point cut, advice

After reading the above theories, I believe everyone is still confused, and so am I. Here are simple examples to deepen the understanding of aspect, jointpoint, pointcut and advice in AOP

Suppose, there used to be a small county called Java. On a dark and windy night for a month, a murder occurred in this county. The murderer was very cunning, and there were no valuable clues left on the scene. Fortunately, Gang The old Wang, who came back from next door, accidentally discovered the murderer's process at this time, but because it was late and the murderer was covering his face, the old Wang did not see the murderer's face clearly. He only knew that the murderer was a male, about his height. Seven feet five inches. The county magistrate of Java County, according to the description of the old king, ordered the soldiers guarding the gate: Any man who is found to be seven feet five inches tall must be arrested and interrogated. Of course, the soldiers dare not violate the county magistrate’s orders. , I had to arrest all qualified people who entered and left the city.

Let's take a look at the corresponding relationship between the above story and AOP.
First of all, we know that in Spring AOP, join point refers to the execution point of all methods, and point cut is a description information, which modifies join point, via point cut, we can determine which join point can be woven into Advice. correspond to our example above, we can do a simple analogy, join point is equivalent to Java's small town people , point cut is equivalent to the allegations made by Pharaoh, that the murderer was a man, standing about seven feet five inches , while the advice is applied in line with the suspect Wang described the action: grasping for questioning .
Why can this analogy it ?

  • join point --> people in a small county in Java: because by definition, join points are all candidate points that may be woven into advice. In Spring AOP, all method execution points can be considered as join points. In our example above, the murder occurred in a small county, and it stands to reason that everyone in this county may be a suspect.
  • point cut --> male, about seven feet five inches tall: We know that all methods (joint points) can be woven into advice, but we don’t want to be woven into advice in all methods, and the role of pointcut is to provide a set of rules to match joinpoint, to meet the rules joinpoint add advice. Similarly, for the magistrate, he then stupid, know that I can put all the people in the county were arrested for questioning, but according 凶手是个男性, 身高约七尺五寸, to meet the requirements of people arrested. here 凶手是个男性, 身高约七尺五寸is a modified predicate, which defines the scope of the murderer, meet this modified rule people are suspects, arrested and interrogated needs.
  • advice --> Grab it for interrogation. Advice is an action, that is, a piece of Java code. This piece of Java code acts on the join points defined by the point cut. In the same way, compared to our example, 抓过来审问this action is right meet those acting on 男性, 身高约七尺五寸the 爪哇的小县城里的百姓.
  • Aspect: aspect is a combination of point cut and advice, so here we can make an analogy: "According to the clues of Lao Wang, all men who are found to be seven feet and five inches tall must be caught and interrogated." This whole action can be considered It is an aspect.

reference

https://segmentfault.com/a/1190000007469968

Use Spring to implement AOP

Use AOP weaving, to import an aspect dependency package

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>

excution expression:

​ For example, define the entry point expression execution (* com.sample.service.impl...*. *(...)) <------ all methods of all classes

  1. execution(): The body of the expression.
  2. The first number: indicates the return type, and the number indicates all types.
  3. Package name: indicates the name of the package that needs to be intercepted. The two periods after it indicate the current package and all subpackages of the current package, the
    com.sample.service.impl package, and the methods of all classes under the descendant package.
  4. The second number: indicates the class name, and the number indicates all classes.
  5. (...): The last asterisk represents the method name, the number represents all methods, the following parentheses represent the method parameters, and two periods represent any parameters

Method 1: Use Spring's API interface to achieve

<!--    方式一:使用原生SpringAPI接口-->
<!--    配置AOP:需要导入aop 的约束-->
    <aop:config>
        <!--切入点:expression:表达式,execution(要执行的位置!* * * *)-->
        <aop:pointcut id="pointcut" expression="execution(* com.feng.service.UserServiceImpl.*(..))"/>

        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

Method 2: Customize the class to implement AOP

[Mainly the definition of the aspect]

<!--方式二:自定义类-->
    <bean id="diy" class="com.feng.diy.DiyPointCut"/>
        <aop:config>
            <aop:aspect ref="diy">
                <!--切入点-->
                <aop:pointcut id="point" expression="execution(* com.feng.service.UserServiceImpl.*(..))"/>
                <!--通知-->
                <aop:before method="before" pointcut-ref="point"/>
                <aop:after method="after" pointcut-ref="point"/>
            </aop:aspect>
        </aop:config>

Method 3: Realize through annotations

<!--    方式三-->
    <bean id="annotationPointCut" class="com.feng.diy.AnnotationPointCut"/>
<!--    开启注解支持!-->
    <aop:aspectj-autoproxy/>

AnnotationPointCut.java

package com.feng.diy;
//方式三:使用注解方式实现AOP
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
//标注这个类是一个切面
public class AnnotationPointCut {
    
    

    @Before("execution(* com.feng.service.UserServiceImpl.*(..))")
    public void before(){
    
    
        System.out.println("=====方法执行前=====");
    }

    @After("execution(* com.feng.service.UserServiceImpl.*(..))")
    public void after(){
    
    
        System.out.println("=====方法执行后=====");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.feng.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
    
    
        System.out.println("环绕前");
        Object proceed = jp.proceed();
        //执行方法
        System.out.println("环绕后");

//        Signature signature = jp.getSignature();//获得签名
//        System.out.println("signature:"+signature);
//        System.out.println(proceed);
    }
}

Insert picture description here

Implementation

https://blog.csdn.net/java_cxrs/article/details/108372459

Common Question

Describe Spring AOP

Spring AOP (Aspect Oriented Programming) is a supplement to OOPs (Object Oriented Programming) and it also provides modularity. In object-oriented programming, the key unit is the object, and the key unit of AOP is the aspect, or focus (it can be simply understood as an independent module in your program). Some aspects may have centralized code, but some may be scattered or mixed together, such as logs or transactions. These scattered aspects are called crosscutting concerns . A cross-cutting concern is a concern that can affect the entire application, and should be concentrated as much as possible to one place in the code, such as transaction management, permissions, logging, and security.
AOP allows you to use simple and pluggable configurations to dynamically add cross-cutting concerns before, after, or around the actual logic execution. This makes the code easier to maintain now and in the future. If you are using XML to use aspects, to add or remove concerns, you do not need to recompile the complete source code, but only need to modify the configuration file.
Spring AOP is used in the following two ways. But the most widely used method is Spring AspectJ Annotation Style (Spring AspectJ Annotation Style)

  • Use AspectJ annotation style
  • Use Spring XML configuration style

What is the difference between AOP's focus and cross-cutting focus in Spring

We want to summarize the implemented behaviors in the application modules . The focus can be defined as: the way we want to solve a specific business problem. For example, in e-commerce applications, different concerns (or modules) may be inventory management, shipping management, user management, etc.

Cross-cutting concerns are concerns that run through the entire application . Like logging, security, and data conversion, they are required in every module of the application, so they are a cross-cutting concern.

What are the available implementations of AOP?

The main AOP implementations based on Java are

1、AspectJ

2、SpringAOP

3、JBossAOP

What are the different notification types in Spring

Advice is the implementation of cross-cutting concerns that you want to apply to other modules in your program. Advie mainly has the following 5 types:

1. Before Advice : Advice executed before the connection point, but unless it throws an exception, it has no ability to interrupt the execution flow. Use the **@Before** annotation to use this advice.

2. After Retuning Advice : Advice executed after the connection point is normal. For example, a method returns normally without throwing an exception. Follow **@AfterReturning** to use it.

3. After Throwing Advice : If a method exits by throwing an exception, the Advice will be executed. General **@AfterThrowing** annotation to use.

4. After Advice : Regardless of how the connection point exits (normal return or throwing an exception), these Advices will be executed after the end. Use **@After** annotations.

5. Around advice (Around Advice) : Advice executed around the connection point, you only call a method. This is the most powerful Advice. Use **@Around** annotations.

What is SpringAOP proxy?

Agency is a very widely used design pattern. Simply put, the role of the agent is to control the access to the object through the agent. SpringAOP is implemented based on proxy. AOP proxy is an object created by the AOP framework to implement aspect protocols at runtime.

SpringAOP uses standard JDK dynamic proxy for AOP proxy by default. This allows any interface (or collection of interfaces) to be proxied. SpringAOP can also use CGLib proxy. This is necessary for proxy classes, not interfaces.

If the business object does not implement any interface then CGLib is used by default.

What is introduction (Introduction)?

Introduction allows an aspect to declare that the notified object implements any additional interfaces that they do not actually implement , and provide the implementation of interfaces for these objects. Use the **@DeclareParaents** annotation to generate an introduction.

What are Joint Point and Point cut?

A connection point is a point of program execution. For example, the execution of a method or the handling of an exception. In SpringAOP, a connection point always represents a method execution. That is, all the methods in our own defined interface can be considered as a connection point, if you use cross-cutting concerns in these methods.

The pointcut (pointcut) is an assertion or expression that matches the connection point . Advice is associated with the pointcut expression, and runs at any point of attachment pointcut matching (for example, expression execution(*EmployeeManager.getEmployeeById(...))may be matched EmployeeManagerinterface getEmployeeById()). The concept of connection points matched by pointcut expressions is the core of AOP. Spring uses the AspectJ pointcut expression language by default.

What is weaving?

These methods use words of crosscutting concerns.

The pointcut (pointcut) is an assertion or expression that matches the connection point . Advice is associated with the pointcut expression, and runs at any point of attachment pointcut matching (for example, expression execution(*EmployeeManager.getEmployeeById(...))may be matched EmployeeManagerinterface getEmployeeById()). The concept of connection points matched by pointcut expressions is the core of AOP. Spring uses the AspectJ pointcut expression language by default.

What is weaving?

The Spring AOP framework only supports a limited number of AspectJ pointcut types, which allow the aspect to be applied to the beans declared in the IoC container. If you want to use additional pointcut types or apply aspects to classes created outside of the Spring IoC container, then you must use the AspectJ framework in your Spring programs and use its weaving features.

Guess you like

Origin blog.csdn.net/weixin_43876186/article/details/108629877