当前位置:首页 > 编程笔记 > 正文
已解决

Spring Boot面向切面加注解

来自网友在路上 159859提问 提问时间:2023-11-02 00:14:16阅读次数: 59

最佳答案 问答题库598位专家为你答疑解惑

一.项目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;}}
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Spring Boot面向切面加注解":http://eshow365.cn/6-29732-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!