This is the 26th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”
❤️ About the author: Hello everyone, I am Xiao Xu Zhu. Java field quality creator 🏆, CSDN blog expert certification 🏆, Huawei Cloud enjoy expert certification 🏆
❤️ technology live, the appreciation
❤️ like 👍 collect ⭐ look again, form a habit
Review:
Spring Framework – Understanding the Spring Framework (part 1)
Spring Framework – Understanding IOC (2)
AOP review
What is the AOP
Oriented programming Aspect-oriented programming
What does AOP do
Business logic can be isolated from system-level services
System-level services such as system logging, transactions, permission validation, and so on
How to use AOP
A dynamic proxy
AOP advantages
1. The coupling between components is reduced and the decoupling between software layers is realized
2, low intrusive design, code pollution is very low
3. It is easy to implement functions such as permission interception, runtime monitoring and system logging
To explore the AOP
If you have not been exposed to AOP (aspect oriented programming), you may not be able to understand it for a while, because you are using JAVA object Oriented programming (OOP), no matter, step by step with me to learn AOP.
Of course, if you are a technical bull, since you took the time to check the article of Xu Zhu, welcome to correct the deficiencies and defects in the article.
Let’s start with a code snippet from Mastering Spring4.x Enterprise Application Development
The business code in the diagram is surrounded by transaction management code and performance monitoring code, and as anyone who has learned JAVA knows, there is duplicate code. When duplicate code occurs, it is necessary to refactor the code. There are two steps for refactoring the code:
1. Drawing method
2, draw into the class
The method of extraction into classes is called vertical extraction
- Vertical extraction is realized by inheritance
However, Huizhu found that this method of extraction was not applicable to the business in the diagram, because the transaction management code and performance monitoring code are logically related to the corresponding business code
Now that vertical extraction is no longer possible, AOP wants to extract the same code that is scattered across the business logic code into a separate module by cutting it horizontally! Please see below
The diagram should make sense. It’s easy to horizontally extract repetitive non-business code. But how to merge the non-business code into the business code to achieve the same effect as the previous code. This is the conundrum, the one AOP will solve.
AOP principle
The underlying principle of AOP is dynamic proxying (if you haven’t heard of the proxy pattern, check out his blog explaining proxy patterns to his girlfriend)
The fourth edition of Spring Training
Spring AOP is built on dynamic proxies, so Spring’s support for AOP is limited to method interception.
AOP’s dynamic proxy:
- JDK dynamic proxy
- Cglib dynamic proxy
Spring uses JDK dynamic proxy versus CGLiB dynamic proxy based on:
(1) Spring uses JDK dynamic proxies when beans implement interfaces
(2) Spring uses CGlib as an implementation when the Bean does not implement the interface
< AOP :aspectj-autoproxy proxy-target-class=”true”/>
JDK proxy or CGLib proxy which should we use
In “Mastering spring4.x Enterprise Application Development combat” gave suggestions:
If it is a singleton, it is best to use the CGLib proxy. If it is a multi-instance, it is best to use the JDK proxy
The reason:
The JDK performs better when creating proxy objects than CGLib proxies, while generating proxy objects performs worse than CGLib proxies.
For a singleton agent, CGLib is recommended
Now do you know what AOP is: horizontal extraction of non-business duplicate code and dynamic proxy weaving into target business object functions to implement the same code as before
AOP terminology
Aop terminology is hard to understand, and it’s covered in mastering Spring4.x Enterprise Application Development, which I’ll try to explain
The join (JointPoint)
All methods in a class can be called join points
Point (PointCut)
As mentioned above, each method can be called a join point, and when we locate a specific method, it becomes a tangency point.
Using annotations, methods defined by @log are pointcuts
Enhancements/Advice
Represents a piece of logical code added to a pointcut and locates the orientation information of the join point.
MethodBeforeAdvice
Pre-notification is executed before the target method is executed
After Turning Advice
Postnotification is executed after the target method has executed. You can get the value returned by the target method, but cannot change the value returned
Circular notification (MethodInterceptor)
The loop notification has code before and after the target method executes, and you can get the value of the target method, and you can change the return value!
Expand knowledge:
There are two types of interceptors in Spring:
1, HandlerInterceptor
2, MethodInterceptor
The HandlerInterceptor is an interceptor in the springMVC project that intercepts the requested address before the MethodInterceptor
A MethodInterceptor is an interceptor in an AOP project that intercepts methods, even if they are not methods in a Controller.
Exception Advice
The most suitable scenario is transaction management
IntroductionInterceptor
Introduction notifications are special in that each of the above four types of notifications is woven into the target method, while introduction notifications add a new method or attribute to the target class
- It simply defines what it does, where it does it
- Spring AOP provides five types of Advice for us: pre-advice, post-advice, return Advice, exception Advice, and surround Advice for us to use!
Section (Aspect)
The aspect consists of pointcuts and enhancements/notifications
System services, such as security verification, transaction processing, and logging, that intersect business logic can be understood as facets
Weave (has)
This is the process of inserting aspect code into a method of the target object, equivalent to the contents of the invocationHandler interface method in the JDK dynamic proxy
Annotation explanation: is in the target object on a method, type a section annotation
Target Object
Classes to which pointcuts and join points belong
Consultant (Advisor)
An encapsulation and extension of advice that can be woven into more complex ways into some methods is an assembler that wraps advice into more complex facets.
Spring’s support for AOP
Spring provides three types of AOP support:
- Proxy-based classic SpringAOP
- You need to implement the interface and manually create the proxy
- Pure POJO section
- Use XML configuration, AOP namespace
@AspectJ
Annotation-driven facets- This is the simplest and most convenient way to use annotations!
knowledge
There are three main types of section
- General aspects
- Cutting plane
- Introduce/introduce the cut
General section, point section, introduction/introduction section Description:
The general section is generally not directly used, the point section is directly used.
The introduction/introduction facets are highlighted here:
- Introduction/Introduction facets are introduction/introduction enhanced wrappers that make it easier to add implementations of any interface to existing objects by introducing/introduction facets!
Inheritance diagram:
The introduction/introduction aspect has two implementation classes:
- DefaultIntroductionAdvisor: common implementation class
- DeclareParentsAdvisor: An introduction/introduction aspect for implementing AspectJ’s DeclareParent annotation representation
In fact, we tend to use AOP internally in Spring to create proxies for us using BeanPostProcessor.
The creators of these agents can be divided into three categories:
- Automatic proxy creator based on Bean configuration name rules: BeanNameAutoProxyCreator
- Based on Advisor matching mechanism of automatic proxy creator: it will scan all the Advisor, the container for DefaultAdvisorAutoProxyCreator implementation class
- Based on AspectJ annotations in the Bean label automatic proxy creator: AnnotationAwareAspectJAutoProxyCreator
Corresponding class inheritance diagram:
Introduce new methods to the Bean using the introduction/import implementation
In fact, pre notification, post notification, or wrap notification, these are all fairly straightforward. The whole article on the introduction/introduction section is more interesting, let’s try to implement it
There is a server interface:
public interface Waiter {
// Greet guests
void greetTo(String clientName);
/ / service
void serveTo(String clientName);
}
Copy the code
Corresponding attendant interface implementation class:
@Service("Waiter") public class NaiveWaiter implements Waiter { @Override public void greetTo(String clientName) { System.out.println("NaiveWaiter:greet to " + clientName + "..." ); } @Override public void serveTo(String clientName) { System.out.println("NaiveWaiter:serve to " + clientName + "..." ); }}Copy the code
Now I want to do is: think this waiter can act as a salesman’s role, can sell things! Of course, I’m definitely not going to add a method to sell something to the Waiter interface because it’s temporary
So, I set up a salesperson interface:
public interface Seller {
int sell(String goods, String clientName);
}
Copy the code
Salesman interface implementation class:
public class SmartSeller implements Seller {
@Override
public int sell(String goods, String clientName) {
System.out.println("SmartSeller: sell "+goods +" to "+clientName+"...");
return 100;
}
}
Copy the code
The class diagram looks like this:
Now what I want to do is: use AOP’s introduction/introduction facets to enable our servers to sell things too!
Our lead-in/lead-in section looks like this:
@Component @Aspect public class EnableSellerAspect { @DeclareParents(value = "com.yiyu.kata.util.aop.NaiveWaiter", DefaultImpl = smartSeller.class) // Public Seller; // Target interface}Copy the code
Now that I’ve written this section class, guess what happens?
The answer is: Slice technology fuses SmartSeller into NaiveWaiter so that NaiveWaiter implements the Seller interface !!!!
It’s amazing, isn’t it? Let’s test it
public class TestAop { @Test public void testAop(){ ApplicationContext ac = new ClassPathXmlApplicationContext("dispatcher-servlet.xml","applicationContext-datasource.xml","applicationContext.xml"); Waiter waiter = ac.getBean("Waiter",Waiter.class); // Call waiter. GreetTo (" empty bamboo "); Waiter. ServeTo (" falsely bamboo "); // We have implemented the Seller interface by introducing/introducing section, so we can cast the Seller = (Seller) waiter; Buyer.sell (" seller ", "dummy "); }}Copy the code
The result: Amazing, hahaha
The specific call process is as follows:
conclusion
- The underlying implementation of AOP is dynamic proxies, which include JDK dynamic proxies and CGLib proxies. Spring uses the JDK’s dynamic proxy when the Bean implements the interface; When the Bean does not implement the interface, Spring uses CGlib as the implementation; You can force the use of CGlib.
- For single instances, the CGLib proxy is recommended. For multiple instances, the JDK proxy is recommended. Because CGLib proxy objects run faster than JDK proxy objects
- AOP’s layer is method-level and only intercepts methods
- Whether XML or annotation, the principle is the same, we use annotation AOP is enough, easy to use
- The introduction/introduction aspect is more interesting to implement, as illustrated above, it can achieve the effect of using an interface method without invading the code, low coupling effect. Specific beauty is still to be developed, the discovery behind and then supplementary explanation
References:
- Proficient in Spring4.x Enterprise Application Development