preface
This article, the fifth in the “How to Implement a Simple Version of Spring” series, starts with an introduction to IoC, one of the core technologies in Spring, and takes a look at another important Spring technology — AOP. For those of you who have developed with the Spring framework, you are more or less familiar with AOP, which is described in Chinese as faceted programming. It is crucial to learn a new technology and understand its background. Did you think about it when you first started with AOP? Why do you need AOP when you already have OOP in an object-oriented language? To put it another way, what are the scenarios in OOP that are not handled elegantly and need to be addressed by a new technique? (P.S. suggests a 10-second pause to think for yourself…)
Why YOU need AOP
We do the final purpose of software development is to solve the company’s various needs, for your business can assign, note that the demand here includes the business requirements and system requirements, for the vast majority of the business needs of the common concerns, can through the way of object-oriented (OOP) for its good abstraction, encapsulation, and modularity, However, although the use of object-oriented method for system requirements is very good to decompose and modularize it, but it can not very good to avoid these similar system requirements scattered everywhere in the system of each module.
Therefore, we need to find a better way, which can provide a new set of methods to deal with the above problems on the basis of OOP, or make a supplement to OOP object-oriented development mode, so that it can deal with the above problems more gracefully. One solution Spring has provided so far is faceted programming — AOP. With AOP, we can modularize system requirements such as transaction management, system logging, and security checks, making the whole system more modular for subsequent management and maintenance. If you are careful, you will notice that a key abstraction introduced into AOP is aspects, which encapsulate cross-cutting concerns in a system. It is important to make it clear that AOP and OOP are not binary. AOP is a complement to OOP. Aspects can collaborate to fulfill requirements, and aspects are as important to AOP as classes are to OOP.
A couple of important concepts
Our ultimate goal is to emulate the Spring framework itself to implement a simple version of AOP, although it is a simple version but will cover the core ideas and main implementation steps of Spring AOP, but before that, let’s take a look at the important concepts in AOP, but also to lay the theoretical foundation for future implementation. One caveat here is that I won’t be using Chinese translations to describe any of these AOP-defined terms (and AOP terminology in the industry is inherently inconsistent). The important thing you need to understand is what the term stands for in AOP, just as we don’t translate Spring as Spring. In software development communication you know it represents a Java development framework. The key terms are described below:
Joinpoint
A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. — Spring Docs
Through introducing the before, before our system running, needs to be some of the definition of AOP crosscutting concerns (module) weave (can be as simple as embedded) to the system of some of the business module, want to accomplish can weave premise is that we need to know in what point, the enforcement point is the Joinpoint. Here’s a simple example:
/ * * *@author mghio
* @sinceThe 2021-05-22 * /
public class Developer {
private String name;
private Integer age;
private String siteUrl;
private String position;
public Developer(String name, String siteUrl) {
this.name = name;
this.siteUrl = siteUrl;
}
public void setSiteUrl(String siteUrl) {
this.siteUrl = siteUrl;
}
public void setAge(Integer age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setPosition(String position) {
this.position = position;
}
public void showMainIntro(a) {
System.out.printf("name:[%s], siteUrl:[%s]\n".this.name, this.siteUrl);
}
public void showAllIntro(a) {
System.out.printf("name:[%s], age:[%s], siteUrl:[%s], position:[%s]\n".this.name, this.age, this.siteUrl, this.position); }}Copy the code
/ * * *@author mghio
* @sinceThe 2021-05-22 * /
public class DeveloperTest {
@Test
public void test(a) {
Developer developer = new Developer("mghio"."https://www.mghio.cn");
developer.showMainIntro();
developer.setAge(18);
developer.setPosition("Shanghai, China"); developer.showAllIntro(); }}Copy the code
Theoretically, in the test() method call in the example above, we could have chosen to weave at the constructor execution time in Developer, or at the execution point of the showMainIntro() method (where it is called or executed inside the method), Or when setAge() sets the SGE field. In fact, you can weave at any of the test() execution points you want, which are joinPoints. The sequence diagram of the test() method call can be used to visualize this:
There are some common Joinpoint types based on the timing of method execution:
- Constructor Call. The execution point at which an object is initialized by calling its constructor, as in the above code
Developer developer = new Developer("mghio", "https://www.mghio.cn");
. - Method Call. The execution point at which a method of an object is called, in fact
Constructor call
This is also a special case of a method call, except that the method is a constructor, as in the exampledeveloper.showMainIntro();
和developer.showAllIntro();
It’s all of these types. - Method Execution. The execution point of the program inside a method when it is called. This is the execution point inside the called method, and
The method call
Different methods are executed as indicated in the sequence diagram above. - Field set. Call object
setter
Method sets the code execution point for an object field. The trigger point is when the object’s properties are set, regardless of how they are set. In the example abovedeveloper.setAge(18);
和Developer. SetPosition (" China. Shanghai ");
It’s all of these types. - Class initialization. Initialization points for some static fields or blocks of static code in the class are not shown in the examples above.
- Exception execution. The execution point of the exception-handling logic after some method of the class throws an exception. This type is not present in the example above.
In theory, any execution point in a program can be used as a Joinpoint. However, there are some types of execution points on which weaving operations can be costly. Therefore, Joinpoint in Spring only supports Method execution (as noted in the Spring documentation), which in fact works for most scenarios.
Pointcut
A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.– by Spring Docs
Pointcut is a kind of Jointpoint expression. When weaving, you need to configure Pointcut according to the configuration of Pointcut, and then weave crosscutting logic to the matching JoinPoints. The first problem we face here: it is possible to express the joinPoints we need to weave into quickly in human natural language, but how to express these JoinPoints in code? There are several ways to express the Joinpoint definition:
- Specify the name of the method to weave in directly. Obviously, this representation is simple, but it supports relatively simple functionality and is only applicable to method types
Joinpoint
And when there are more methods that need to be woven in our system, define the woven one by onePointjoint
Time is too much trouble. - Regular expression mode. Regular expressions, as you probably all know, are powerful enough to match objects that represent multiple method types
Jointpoint
.Spring
Framework of theAOP
This representation is also supported. - Pointcut language-specific mode. Because this is a domain-specific language (
DSL
), so it provides the most flexible and rich functions, which also leads to high complexity in both its use and implementation, such asAspectJ
That’s the way they use it, of courseSpring
Also support.
Pointcut also supports simple logic operations, so you can logically combine multiple simple pointcuts into a more complex Pointcut. Like in the Spring configuration and and or logical operations such as identifiers and AspectJ && and | | and logical operators.
Advice
Action taken by an aspect at a particular join point. Different types of advice include “around”, “Before” and “after” advice. (Advice types are discussed later.) model an advice as an interceptor and maintain a chain of interceptors around the join point.– by Spring Docs
Advice represents a crosscutting logic injected into Joinpoint and is an abstract carrier of crosscutting concern logic. Advice can be divided into the following main types according to the location and function of the execution point:
- Before Advice.
Before Advice
That means it’s matchingJoinpoint
The type executed before the location. If successfully woven into the method typeJoinpoint
, thenBeofre Advice
It will be executed before this method is executed, and it’s also important to note that if you need to execute inBefore Advice
To end the execution of the method, we can use theAdvice
Throws an exception to end the execution of a method. - After Advice. Obviously,
After Advice
Indicates the configuredJoinpoint
The type executed after the location. Can be subdivided intoAfter returning Advice
,After throwing Advice
和After finally Advice
Three types. Among themAfter returning Advice
Represents a matchJoinpoint
Method executes normally (No exception thrown
) after execution;After throwing Advice
Denoting matchedJoinpoint
Method execution after throwing an exception and not returning normally;After finally Advice
Representing the method typeJoinpoint
Is executed either normally or when an exception is thrown.
The severalAdvice
Type in method typeJoinpoint
The execution sequence is as follows:
- Around Advice. This type is the most powerful
Advice
, can matchJoinpoint
Before, after and even terminal originalJoinpoint
In normal cases, the process is executed firstJoinpoint
The execution logic before, and then theJoinpoint
Their own execution process, and finally executionJoinpoint
Then the execution logic. Careful you should find, this is the introduction of the aboveBefore Advice
和After Advice
A combination of types? Yes, it can do both, but it depends on the situationAdvice
Type.
Aspect
A modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented by using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style). — Spring Docs
An Aspect is an abstraction wrapped around the Crosscutting concern in our system, and can contain definitions of multiple Joinpoints and Advice. With AspectJ integrated with Spring, you can also specify an Aspect using @AspectJ-style declarative notation, simply by adding @aspect annotations.
Target object
An object being advised by one or more aspects. Also referred to as the “advised object” implemented by using runtime proxies, this object is always a proxied object. — by Spring Docs
Target objects are typically objects that match the Pointcut declaration criteria and are woven into crosscutting logic. They are normally determined by the Pointcut and vary according to the Pointcut declaration criteria. Now that you have AOP in mind, you can rearrange the examples above, as shown in the following figure:
conclusion
In this paper, first of all, the birth background of AOP technology is briefly introduced, followed by the introduction of several important concepts of AOP for the implementation of our own simple version of AOP to lay a foundation, AOP is a complement and perfect OOP, the listed concepts are only the tip of the iceberg involved in AOP concepts, Those who want to learn more about the relevant concepts can read the official documentation. The next part will introduce some of the basic technologies that AOP implementations rely on. Forwarding and sharing are my support, I will be more motivated to adhere to the original sharing!