1.添加切面依赖
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency>
2.自定义注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Log { String value() default ""; }
3.添加切面
添加component注解自动装配bean到ioc容器中 添加切面注解 @Component @Aspect @Slf4j public class LogAspect { private final LogService logService; ThreadLocal<Long> currentTime = new ThreadLocal<>(); public LogAspect(LogService logService) { this.logService = logService; } /** * 配置切入点,路径为添加自定义注解所在的位置 */ @Pointcut("@annotation(cn.edu.tsu.torox.sysLog.annotation.Log)") public void logPointcut() { // 该方法无方法体,主要为了让同类中其他方法使用此切入点 } /** * 配置环绕通知,使用在方法logPointcut()上注册的切入点 * * @param joinPoint join point for advice */ @Around("logPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { Object result; currentTime.set(System.currentTimeMillis()); result = joinPoint.proceed(); cn.edu.tsu.torox.sysLog.model.Log log = new cn.edu.tsu.torox.sysLog.model.Log("INFO",System.currentTimeMillis() - currentTime.get()); currentTime.remove(); // String request = RequestHolder.getHttpServletRequest(); //业务类,根据需求定义,这里为日志,提前建表,进行crud logService.save("1", "google", "192.168.231.20",joinPoint, log); return result; } /** * 配置异常通知 * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "logPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { cn.edu.tsu.torox.sysLog.model.Log log = new cn.edu.tsu.torox.sysLog.model.Log("ERROR",System.currentTimeMillis() - currentTime.get()); currentTime.remove();; // HttpServletRequest request = RequestHolder.getHttpServletRequest(); logService.save("1", "google", "192.168.231.20", (ProceedingJoinPoint)joinPoint, log); } }
4.具体详细参数在joinPoint对象中
5.将自定义注解添加到相应的控制层方法上
流程:
接口-->控制层--->找到带有自定义注解的方法---->跳入切面--->执行环绕通知中的方法(获取该类的方法)
依赖:若项目使用的数据层技术为Spring-data-jpa则无须单独引入aspectjweaver依赖。