springboot切面返回值_SpringBoot之切面AOP[亲测有效]

springboot切面返回值_SpringBoot之切面AOP[亲测有效]SpringBoot提供了强大AOP支持,我们前面讲解过AOP面向切面,所以这里具体AOP原理就补具体介绍;AOP切面主要是切方法,我们一般搞一些日志分析和事务操作,要用到切面,类似拦截器;@Aspect注解是切面注解类@Pointcut切点定义@Before是方法执行前调用@After是方法执行后调用@AfterReturning方法执行返回值调用Service层本身就可以切入事务,所以我们这类…

大家好,欢迎来到IT知识分享网。

SpringBoot提供了强大AOP支持,我们前面讲解过AOP面向切面,所以这里具体AOP原理就补具体介绍;

AOP切面主要是切方法,我们一般搞一些日志分析和事务操作,要用到切面,类似拦截器;

@Aspect注解是切面注解类

@Pointcut切点定义

@Before是方法执行前调用

@After是方法执行后调用

@AfterReturning方法执行返回值调用

Service层本身就可以切入事务,所以我们这类搞个常用的 切controller层方法

每个执行controller层的方法 都记录下请求Url,访问者IP 执行类方法参数等信息;

定义一个切面类:RequestAspect

springboot切面返回值_SpringBoot之切面AOP[亲测有效]

springboot切面返回值_SpringBoot之切面AOP[亲测有效]

1 packagecom.hik;2

3 importjavax.servlet.http.HttpServletRequest;4

5 importorg.apache.log4j.Logger;6 importorg.aspectj.lang.JoinPoint;7 importorg.aspectj.lang.annotation.After;8 importorg.aspectj.lang.annotation.AfterReturning;9 importorg.aspectj.lang.annotation.Aspect;10 importorg.aspectj.lang.annotation.Before;11 importorg.aspectj.lang.annotation.Pointcut;12 importorg.springframework.stereotype.Component;13 importorg.springframework.web.context.request.RequestContextHolder;14 importorg.springframework.web.context.request.ServletRequestAttributes;15

16 @Aspect17 @Component18 public classRequestAspect {19

20 private Logger log = Logger.getLogger(RequestAspect.class);21

22 @Pointcut(“execution(public * com.hik.controller.*.*(..))”)23 public voidlog() {24

25 }26

27 @Before(“log()”)28 public voiddeoBefore(JoinPoint joinPoint) {29 log.info(“方法执行前…”);30 ServletRequestAttributes sra=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();31 HttpServletRequest request=sra.getRequest();32 log.info(“url:”+request.getRequestURI());33 log.info(“ip:”+request.getRemoteHost());34 log.info(“method:”+request.getMethod());35 log.info(“class_method:”+joinPoint.getSignature().getDeclaringTypeName()+”.”+joinPoint.getSignature().getName());36 log.info(“args:”+joinPoint.getArgs());37 }38

39 @After(“log()”)40 public voiddoAfter(JoinPoint joinPoint){41 log.info(“方法执行后…”);42 }43

44 @AfterReturning(returning=”result”,pointcut=”log()”)45 public voiddoAfterReturning(Object result){46 log.info(“执行返回值:”+result);47 }48

49 }

View Code

execution(public * com.hik.controller.*.*(..)) 这个定义 意思是 对 com.hik.controller包下的任意类,任意方法,任意参数,任意返回值的方法都进行切入

我们测试 StudentController

springboot切面返回值_SpringBoot之切面AOP[亲测有效]

点击提交

控制台显示:

springboot切面返回值_SpringBoot之切面AOP[亲测有效]

这里得到了我们需要的信息;

当然这里用到了日志  springboot推荐logback log4j的升级版 用法基本差不多;

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/24311.html

(0)
上一篇 2023-04-08 16:00
下一篇 2023-04-10 17:00

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信