Spring boot aop record method execution time code example, springaop
This article focuses on the implementation code of spring boot aop recording method execution time, as follows.
In order to optimize the performance, we need to calculate the execution time of each method first. It is too troublesome to output logs directly before and after the method. We can use AOP to add time statistics.
Add dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId></dependency>
Add configuration in application. properties
spring.aop.auto=true
The spring. aop. auto attribute is enabled by default. That is to say, @ EnableAspectJAutoProxy has been added by default after the AOP dependency is introduced. Do not add additional information, such as @ EnableAspectJAutoProxy!
Implementation Code
@ Component @ Aspectpublic class LogAspect {private static final Log LOG = LogFactory. getLog (LogAspect. class);/*** define an entry point. * Explanation :**~ The first * represents any modifier and any returned value .*~ The second * defined in the web package or sub-package *~ The third * arbitrary method *~ .. Match any number of parameters. */@ Pointcut ("execution (* com. wedo. stream. service .. *. *(..)) ") public void logPointcut () {}@ org. aspectj. lang. annotation. around ("logPointcut ()") public Object doAround (ProceedingJoinPoint joinPoint) throws Throwable {// LOG. debug ("logPointcut" + joinPoint + "\ t"); long start = System. currentTimeMillis (); try {Object result = joinPoint. proceed (); long end = System. currentTimeMillis (); LOG. err Or ("++ around" + joinPoint + "\ tUse time:" + (end-start) + "MS! "); Return result;} catch (Throwable e) {long end = System. currentTimeMillis (); LOG. error ("++ around" + joinPoint + "\ tUse time:" + (end-start) + "MS with exception:" + e. getMessage (); throw e ;}}}
Notes
The method after aop cannot return the correct value
This proxy method must return values. Otherwise, no value is returned in the code.
// This is not the right public void doAround (ProceedingJoinPoint joinPoint ){}
Written in the Spring document: Spring AOP uses JDK dynamic proxy or CGLIB to create a proxy for the target object. If the proxy target implements at least one interface, JDK dynamic proxy is used. All interfaces implemented for this target type will be proxies. If the target object does not implement any interfaces, a cglib proxy is created.
JDK dynamic proxy by default, changed to cglib
Summary
The above is all the content of the sample code for the execution time of spring boot aop record method. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!