springboot日志切面通用类实例详解

时间:2021-05-19

1.pom.xml文件导入AOP依赖

<!--aop依赖--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.3.0.RELEASE</version></dependency>

2.pom.xml导入Lombok依赖

<!--Lombok依赖--><dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional></dependency>package jmu.rjc.aspect;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.*;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;//日志切面@Aspect@Componentpublic class LogAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); //包名配置为自己的项目包名即可 @Pointcut("execution(* jmu.rjc.web.*.*(..))") public void log(){} @Before("log()") public void doBefore(JoinPoint joinPoint){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String url = request.getRequestURL().toString(); String ip = request.getRemoteAddr(); String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); RequestLog requestLog = new RequestLog(url,ip,classMethod,args); logger.info("Request : {}",requestLog); } @After("log()") public void doAfter(){ logger.info("---------doAfter-------"); } @AfterReturning(returning = "result",pointcut = "log()") public void doAfterReturn(Object result){ logger.info("Result : {}"+result); } @Data @ToString @AllArgsConstructor @NoArgsConstructor private class RequestLog{ private String url; private String ip; private String classMethod; private Object[] args; }}

3.关于Lombok的注意点

Lombok的使用大大简化了开发过程,提高了开发效率,但是也存在一些隐患.比如强行侵入jar包,JDK版本升级冲突,破坏部分封装性等缺陷,使用前最好和团队商量好

到此这篇关于springboot日志切面通用类的文章就介绍到这了,更多相关springboot日志切面通用类内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章