springboot切面配置
文章目的
记录我网上学习切面的实现过程
此次只是在学习过程中,想要记录请求的过程的一些信息,还会继续学习改进。下面是实现过程:
切点
要实现切面,@Aspect注解不能少,必须告诉spring去识别这个类,@Component为了启动springboot项目的时候扫描到这个类。
@Aspect
@Component
既然是切面类,那切点就不能少。
@Pointcut主要是提供一个切点,而execution据说是个函数,用来匹配连接点
execution(方法修饰符 返回类型 方法名 参数 异常)
其中方法修饰符和异常是可选的
@Pointcut("execution(public * com.example.controller.*.*(..))")
public void sysLog(){
}
准备好切点了,接下来就是五种切面的方法了,
第一种
@Before 前置通知,也叫前置增强。为了保证在高并发情况下可以不会使日志打印顺序乱掉,所以改为了bean,没有使用logger.info这种使用方式。此处的JoinPoint参数,可以加也可以不加,这个类主要提供请求信息的ip,方法名等等。
ThreadLocal<Long> startTime = new ThreadLocal<Long>();
@Before("sysLog()")
public void doBefore(JoinPoint joinPoint){
startTime.set(System.currentTimeMillis());
//请求消息
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String str = (String) request.getSession().getAttribute("name");
String username = request.getParameter("username");
// 记录下请求内容
SysLogBean bean = new SysLogBean();
bean.setId(UUID.randomUUID().toString().replace("-",""));
bean.setUsername(username);
bean.setIp(request.getRemoteAddr());
bean.setMethodName(request.getMethod());
bean.setClassName(joinPoint.getSignature().getDeclaringTypeName()+":"+joinPoint.getSignature().getName());
bean.setCreateDate(new Date());
bean.setRemoteHost(request.getRemoteHost());
bean.setUrl(request.getRequestURL().toString());
sysLogService.insertSysLog(bean);
}
第二种
后置通知,或者后置增强。ret是方法的返回值,我没有用到。
@AfterReturning(returning = "ret",pointcut = "sysLog()")
public void doAfterReturn(Object ret){
//记录日志过程消费时间
log.info("time : " + (System.currentTimeMillis()-startTime.get()));
}
第三种
当方法抛出异常时执行,这块的异常可以通过我们做全局异常,抛出我们想要的东西。
//这是我注入的全局异常的类
@Autowired
private ExceptionHandle exceptionHandle;
//后置异常
@AfterThrowing("sysLog()")
public void doAfterThrews(JoinPoint joinPoint){
}
第四种
后置通知或后置增强
//后置通知,都会执行
@After("sysLog()")
public void doAfter(JoinPoint joinPoint){
}
第五种
环绕通知或环绕增强
@Around("sysLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
}
最重要的一点不要忘了导入jar包,或者maven依赖
<!-- 实现切面 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
目前还在学习改进,简单记录,防止忘记!!!!!!