Spring Boot面向切面加注解

一.项目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 {

    @Override
    public 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;
        }
    }
相关推荐
天若有情6738 分钟前
打破思维定式!C++参数设计新范式:让结构体替代传统参数列表
java·开发语言·c++
亲爱的非洲野猪13 分钟前
从ReentrantLock到AQS:深入解析Java并发锁的实现哲学
java·开发语言
wheelmouse778815 分钟前
如何设置VSCode打开文件Tab页签换行
java·python
yangminlei18 分钟前
Spring Boot——日志介绍和配置
java·spring boot
云上凯歌21 分钟前
02 Spring Boot企业级配置详解
android·spring boot·后端
廋到被风吹走24 分钟前
【Spring】Spring Boot Starter设计:公司级监控SDK实战指南
java·spring boot·spring
码头整点薯条29 分钟前
启动报错:Invalid value type for attribute ‘factoryBeanObjectType‘ 解决方案
java
沛沛老爹29 分钟前
Web开发者进阶AI:Agent Skills-深度迭代处理架构——从递归函数到智能决策引擎
java·开发语言·人工智能·科技·架构·企业开发·发展趋势
工具罗某人32 分钟前
docker快速部署kafka
java·nginx·docker
秋饼34 分钟前
【手撕 @EnableAsync:揭秘 SpringBoot @Enable 注解的魔法开关】
java·spring boot·后端