In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you how to understand the Java SpringAOP section class, the content is very detailed, interested friends can use for reference, I hope it can be helpful to you.
What is the facet class?
To put it simply, it dynamically adds the specified code to the specified location of the method.
Why do you need facet classes?
In the process of software development, there are many businesses, especially when writing the core business, often need a lot of other auxiliary business, such as authentication (bank transfer requires authentication), data cache, log output. These are often in the auxiliary part of a core business. A characteristic of these auxiliary tasks is that these businesses are all in the same aspect of the core business.
What do you mean?
If there are four methods of addition, subtraction, multiplication and division, the method start position and the method end position are just a sign, and the method execution position is the core business, and we want to perform some preparatory operations in front of the core code of these four methods. then we can add a piece of code between the method start position and the method execution position, so these preparation operations are actually on the same plane. By the same token, a cut anywhere in the four methods is a section.
When do I need to use the facet class?
For some methods, extract the same kind of non-core business, and then write the extracted business into an aspect class, which can be; for example, add, subtract, multiply and divide, add the log function, then the log function is the non-core business.
What's the use of the noodle class?
To solve the problem of code confusion, non-core business and core business code in the same method will affect the quality of the code, and may even affect the core business.
Let's use the log function to explain how the aspect class creates the log.
Display our incoming data before data processing
Return when an exception is encountered
End of processing shows that the processing is complete
How to implement the log
The easiest way is to output manually before data processing.
Public void receiveMoney (int receiveMoney) throws ReceiveMoneyException {System.out.println ("[collecting money]: parameter is" + receiveMoney); System.out.println ("collecting money] data processing. ; checkAmount (receiveMoney); System.out.println ("data processing transaction completed");}
In this way, our logging function can be realized, but this is only one of the auxiliary businesses, there are many businesses in a project, all kinds of tedious functions and logs are implemented in one method, and the code structure will be extremely confusing. In particular, when a logging function is put together with the core function, it is easy to have problems, and there are often many other non-core businesses in a business that need to be dealt with. For example, before accepting the money, you need to verify your identity. Banks with unknown sources cannot receive the money directly. If the identity verification is correct, then you have to cache the data after receiving the money.
Non-core businesses such as authentication, data caching and exception handling will often lead to confusion in the code structure of the core business if they are not handled properly.
So how can logging function and authentication be added to the core business method without affecting the code of the core business?
The aspect class can accomplish these tasks.
The aspect class can dynamically add the specified code at the specified location.
Five notices of AOP
AspectJ supports five types of notification comments:
@ Before: pre-notification, executed before the method is executed
@ After: post notification, executed after the method is executed
@ AfterRunning: returns the notification, which is executed after the method returns the result
@ AfterThrowing: exception notification, after the method throws an exception
@ Around: surround the notification and execute around the method
What's the notice? The simple understanding is that the auxiliary business mentioned above. When we extract the auxiliary business code in the division aspect, there will be the following situations
The auxiliary business needs to be executed before the core business.
The auxiliary business needs to be executed after the core business is executed.
The auxiliary service needs to be performed when an error is reported.
The auxiliary business needs to be executed when the result is returned.
The auxiliary business needs to be executed in the event of an exception before and after the method execution
Post notice and return notice if you need to find out above
Return notification (after-returning): when the core business code is executed, it will not be executed if an exception occurs.
Post notification (after): executes regardless of whether the target method has an exception or not. if there is no exception, the execution order is after the notification is returned.
Implementation Technology of Spring AOP Class
Dynamic proxy (InvocationHandler): the native implementation of JDK, the target class that needs to be proxied must implement the interface. Because this technology requires the proxy object and the target object to implement the same interface (two sibling subpatterns).
Cglib: the proxy is implemented by inheriting the proxied target class (godfather recognition pattern), so the target class is not required to implement the interface.
AspectJ: essentially a static proxy, the agent logic is "woven" into the bytecode file compiled by the proxied target class, so the final effect is dynamic. Weaver is the weaver. Spring simply borrows annotations from AspectJ.
I. preparatory work
Add the following code to the pom.xml of maven
4.0.0 org.example Spring-AOP 1.0-SNAPSHOT 8 8 org.springframework spring-context 5.3.14 org.springframework spring-aspects 5.3.14 org.springframework spring-test 5.3.14 org.aspectj aspectjweaver 1.9.7 junit junit 4.13.2 test
Because we are using annotations in AspectJ, we need to import
Org.aspectj aspectjweaver 1.9.7
Springconfig
Test class
@ RunWith (SpringJUnit4ClassRunner.class) / / this requires a spring-test dependency. There is no need to create an IOC container @ ContextConfiguration (value = "classpath:applicationContext.xml") public class AOPTEST {@ Autowired private Calc calc; @ Test public void testAnnotationAOP () {int add=calc.add (10Power0); System.out.println ("external add" + add);}}
In this article, we first write aspect classes in the form of interfaces.
File structure
What is in the facet class?
Before: executes a piece of code before the target method executes
Post notification (AfterReturning): executes after the target party completes execution. If the target method is abnormal, the post notification will no longer execute a piece of code.
Exception notification (Afterthrowing): executes a piece of code when the target method throws an exception
Final notification (After); executes regardless of whether the target method has an exception or not, which is equivalent to try. Catch... Finally in finally.
Around: you can control whether the target method executes or not
What is the use of these notices?
There is no need to add extra code inside the core code, but to call some part of the code before, after, after, and at the end of the core code.
The knowledge of reflection is involved here, because the underlying implementation of these notifications is dynamic proxies or cglib. To put it simply, before calling the core code, the called method is intercepted and a piece of code in the facet class is executed.
Why is it named facet class?
First of all, it is important to know that aspect classes can be faceted by many methods or classes, depending on what you want to achieve. For example, if we want to invoke the logging function before the method is executed, we need to "cut" these methods before execution, and then "add" the log output to the method. Because these things are done by aspect classes, they have such a name.
Let's look at the code.
Facet class
@ Aspect@Componentpublic class LogAspect {/ / pre-notification @ Before (value = "execution (public int com.Calc.add (int, int))") public void printLogBefore () {System.out.println ("[AOP pre-notification] method starts") } / / Post notification @ AfterReturning (value = "execution (public int com.Calc.add (int, int) / / getting the return value of the target method in the return notification is divided into two steps: give returning a name, and then use that name to declare a corresponding formal parameter public void printLogAfterSuccess () {System.out.println (" [AOP return notification] method returned successfully ") in the notification method. } / / exception notification @ AfterThrowing (value = "execution (public int com.Calc.add (int, int))") public void printLogAfterException () {System.out.println ("[AOP exception notification] method throws an exception") } / / end notice @ After ("execution (public int com.Calc.add (int, int))") public void printLogFinish () {System.out.println ("[AOP end notice] method ends");}}
Let's take a look at the test method.
@ Test public void testAnnotationAOP () {int add=calc.add (10jin0); / / call System.out.println ("external add" + add);}
Results:
As you can see, the aspect class successfully implements the logging function in Calculator.
On how to understand the Java SpringAOP aspect class to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.