栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot aop 记录方法执行时间代码示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot aop 记录方法执行时间代码示例

本文研究的主要是spring boot aop 记录方法执行时间的实现代码,具体如下。

为了性能调优,需要先统计出来每个方法的执行时间,直接在方法前后log输出太麻烦,可以用AOP来加入时间统计

添加依赖
  
 org.springframework.boot  
 spring-boot-starter-aop
在application.properties中加入配置
spring.aop.auto=true

spring.aop.auto属性默认是开启的,也就是说只要引入了AOP依赖后,默认已经增加了@EnableAspectJAutoProxy。 切记千万不要加入多余的信息,如@EnableAspectJAutoProxy!

实现具体代码
@Component
@Aspect
public class LogAspect {
	private static final Log LOG = LogFactory.getLog(LogAspect.class);
	
	@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.error("+++++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;
		}
	}
}
注意问题

aop后方法不能正确返回值

这个代理方法一定要返回值,否则,在代码中就没有返回值了。

//这样是不对的
 public void doAround(ProceedingJoinPoint joinPoint){}

Spring的文档中这么写的:Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理。所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理。

默认是JDK动态代理,更改为cglib

总结

以上就是本文关于spring boot aop 记录方法执行时间代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/141817.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号