In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail what is the running order of multi-facets in Spring AOP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Spring AOP multi-section operation sequence
When the execution of a method is tangent by multiple facets, the surround notification only affects the notification order of the current aspect, for example, creating two facets logUtil,validateUtil and two facets together to monitor the addition operation of the calculator class, add (int aline int b); in the test, depending on the initials of the facet tool class, the execution order of amurz is by default, so the logUtil aspect notification executes the notification before validateUtil
So the order is: pre-notification of L-- pre-notification of > v-> execute the add method, and then post notification of v-> post return of V-> post notification of L-> post return of L.
However, when surround notifications are added to logUtil, surround notifications are executed before normal notifications in logUtil. Surround notifications are very powerful. We can change the parameters of this method before executing the method through reflection, but ordinary notifications cannot do so. Although a surround notification is added to logUtil, this surround notification is only executed before the ordinary notification of logUtil, and it does not affect the execution order of ordinary notification of validateUtil, so the execution order of surround notification is
Circle Front-> log Front-> va Front-> Target method-> va Post-> va return-> orbit return Notification-> orbit Post-> log Post-> log return.
Figure:
The validate section here is the VaAspect in the figure.
By the way, you can change the default order of aspects. To add @ order (int value) annotation to the aspect class to be changed, the default value is very large, and the larger the value, the lower the priority of execution, so if you set it to 1, you will first execute the notification of this aspect.
Application scenarios of AOP
Aop can log.
Aop can do permission verification.
AOP can do security check.
AOP can do transaction control.
Recall annotation-based AOC configuration
Add both the target class and the aspect class to the IOC container. @ Component
Tell Spring which is the aspect class @ Aspect
Use five notification annotations in the aspect class to configure when these methods in the aspect will run there
Turn on the aop function of annotations.
AOP configuration is implemented without annotations.
1. Facet class
Public class LogUtil {public void performance () {} public void logStart (JoinPoint joinPoint) {/ / get the parameter list on the method Object [] args = joinPoint.getArgs (); / / get the method signature Signature signature = joinPoint.getSignature (); String name = signature.getName (); / / get the method name System.out.println ("advance notice:" + name+ "method begins to execute. The parameters are: "+ Arrays.asList (args) +");} public void logReturn (JoinPoint point,Object result) {String name = point.getSignature (). GetName (); Object [] args = point.getArgs (); System.out.println ("return notification: the" + name+ "method executes normally, and the return result is" + result+ ""). } public void logException (JoinPoint point,Exception e) {String name = point.getSignature () .getName (); System.out.println ("exception notification: there is an exception in the" + name+ "method, the exception is" + e + "...");} public void logEnd (JoinPoint joinPoint) {String name = joinPoint.getSignature () .getName () System.out.println ("post notification:" + name+ "method ends");} / / surround notification public Object myAround (ProceedingJoinPoint proceedingJoinPoint) {Object proceed = null; / / get the method name String name = proceedingJoinPoint.getSignature (). GetName (); / / get the parameter list of the execution method Object [] args = proceedingJoinPoint.getArgs () Try {System.out.println ("surround pre-notification:" + name+ "method starts execution, parameter is" + Arrays.asList (args) + ""); / / equals method.invoke (); execution of the specified method proceed = proceedingJoinPoint.proceed () through reflection; System.out.println ("surround return notification:" + name+ "method returns the result is" + proceed+ ";) } catch (Throwable throwable) {System.out.println ("surround exception notification: exception is" + throwable+ "); throwable.printStackTrace ();} finally {System.out.println (" surround post notification: "+ name+" method ends ");} return proceed;}
two。 The class that is cut in (here is a calculator class)
Package main.java.cn.zixue.domain;public class MyCalculator {public int add (int a-line int b) {return aint b;} public int sub (int a-line int b) {return aqob;} public int mul (int a-line int b) {return a-line b;} public int dev (int a-line int b) {return a le le b } public double add (double a float bcent int c) {return a float bpenny c;}}
3. Configuration file
4. Test result
@ Testpublic void Test02 () {MyCalculator myCalculator = (MyCalculator) context.getBean ("myCalculator"); myCalculator.add (1Magazine 10); System.out.println ("= =");}
Advance notice: the add method starts to execute. The parameters are: [1,10]
Surround the pre-notification: the add method starts execution with the argument [1, 10]
Circular return notification: the add method returns a result of 11
Surround post notification: the add method is over
Return notification: the add method executes normally. The returned result is: 11
Post notification: the add method is over
= * *
General pre-notification-> surround notification-> surround return-> surround post-> normal return-> ordinary post
When are annotations and configuration files used? How to choose?
The advantage of annotations: the configuration is fast and simple.
The advantages of the configuration file: the function is rich, he can realize all the annotations, and he can also have the annotations without them.
When important aspects are encountered, write with configuration files, such as permission verification and management. Use annotations for common sections.
Spring AOP section execution order and FAQ section annotation execution order public Object aop (Method method,Object object) {try {try {/ * doAround start*/ doBefore (); method.invoke (object); / * doAround end*/} finally {doAfter ();} doAfterReturning () } catch (Exception e) {doAfterThrowing ();}} execution order between sections
Older annotations are used between sections to distinguish the order of calls. The smaller the order value, the more the section is executed first (and then ends).
If Order is not specified, Order is the default-> Integer.MAX_VALUE. If the Order is the same, the section is performed in alphabetical order. For example, if @ Transactional and @ Cacheable- > correspond to TransactionInterceptor and CacheInterceptor, then the @ Cacheable section will be executed first.
@ Transactional is also implemented through aspects, and the order value is Integer.MAX_VALUE. (if a log annotation with older is added to the service method at the same time, an error is reported in the log section after, and the transaction will not be rolled back)
Examples of frequently asked questions
1. Method A calls method B of the same class, and the section on method B will not take effect.
Example of a question:
@ Component public class StrategyService extends BaseStrategyService {public PricingResponse getFactor (Map pricingParams) {/ / do some parameter verification and things related to exception capture return this.loadFactor (tieredPricingParams);} @ Override @ StrategyCache (keyName = "key0001", expireTime = 60 * 60 * 2) private PricingResponse loadFactor (Map pricingParams) {/ / Code execution}}
Reason: the AOP of Spring is called through the proxy object. Only in this way can the proxy object also execute the relevant code before and after the execution of the real object. For the above invocation using this, this is only self-invocation, and will not be called using the proxy object, so the aspect class cannot be executed.
Public static void main (String [] args) {ProxyFactory factory = new ProxyFactory (new SimplePojo ()); factory.addInterface (Pojo.class); factory.addAdvice (new RetryAdvice ()); Pojo pojo = (Pojo) factory.getProxy (); / / this is a method call on the proxy! Pojo.foo ();}
Solution: use AopContext.currentProxy () to get the proxy object, and then call the corresponding method through the proxy object. One more thing to note is that the expose-proxy of Aspect needs to be set to true in the above way.
@ Component public class StrategyService {public PricingResponse getFactor (Map pricingParams) {/ / do some parameter verification and exception catch related things / / instead of using this.loadFactor, we use AopContext.currentProxy () call here to solve the problem that the AOP agent does not support method self-calling if (AopContext.currentProxy () instanceof StrategyService) {return ((StrategyService) AopContext.currentProxy ()) .loadFactor (tieredPricingParams) } else {/ / part of the implementation has not been proxied, then direct self-call can be return loadFactor (tieredPricingParams) } @ Override @ StrategyCache (keyName = "key0001", expireTime = 60 * 60 * 2) private PricingResponse loadFactor (Map oricingParams) {/ / Code execution}} / / there is another thing to note. In the above way, you also need to set the expose-proxy of Aspect to true. If the configuration file is modified: / / if it is SpringBoot, then modify the comments of the application launch entry class: @ EnableAspectJAutoProxy (exposeProxy = true) public class Application {} this article on "what is the running order of multiple aspects in Spring AOP" is shared here. I hope the above content can be helpful to you, so that you can learn more knowledge. If you think the article is good, please 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.