springboot aop 自定义注解形式

发布时间:2024年01月23日

引入pom

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Xxxano{
}

配置切面

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class XxxanoAOP {

    @Pointcut("execution(* com.xx.xxxx.controller..*Controller.*(..)) &&@annotation(com.xx.xxxx.aop.Xxxano)")
    public void pointcut() {
    }

    @Around("pointcut()")
    @SneakyThrows
    public Object arround(ProceedingJoinPoint pjp) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        Object[] args = pjp.getArgs();
        log.info("{}.{}  , param : {}"
                , method.getDeclaringClass().getName()
                , methodName
                , args);

                String head = request.getHeader("head");
                

//                todo: 加判断逻辑
        return pjp.proceed(args);
    }
}

文章来源:https://blog.csdn.net/qq56477643/article/details/135782294
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。