一.项目pom.xml文件引入切面依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二.定义注解类
import java.lang.annotation.*;/*** @desc 错误日志注解* @author lss*/
@Target(ElementType.METHOD) //应用于方法上面
@Retention(RetentionPolicy.RUNTIME) //表示在运行时注解任可用
public @interface ErrorLog {/*** 日志报错类型 */public String type() default "";
}
三.定义切面类,实现方法拦截和异常处理逻辑
import com.qike.sys.annotation.ErrorLog;
import com.qike.sys.service.ErrorResponseService;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;@Aspect
@Component
@RequiredArgsConstructor
public class ErrorLogAspect {private final ErrorResponseService errorResponseService;//切点@Around("@annotation(errorLog)")public Object around(ProceedingJoinPoint joinPoint, ErrorLog errorLog) throws Throwable {// 在方法执行前做些事情System.out.println("Before method execution...");try {// 执行被拦截的方法Object result = joinPoint.proceed();// 在方法执行后做些事情System.out.println("After method execution...");return result;} catch (Exception e) {// 记录错误信息// 注解自定义属性获得值String type = errorLog.type;// 异常逻辑处理...System.out.println("Error occurred: " + e.getMessage());throw e;}}
}
四.在方法中使用
@ErrorLog(type = "2")public void splitLogTable(){}
四.在拦截器中使用
@Slf4j
@Component
public class AppControllerInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {HandlerMethod handlerMethod = (HandlerMethod) handler;try {log.debug(request.getServletPath());// 不用登录的标识ErrorLog loginRestrict = handlerMethod.getMethodAnnotation(ErrorLog.class);// 未登录可以访问if (null != loginRestrict) {return true;}......return true;} catch (Exception e) {e.printStackTrace();return false;}}