创建一个工具类,将@Aspect注解加上(@Aspect:作用是把当前类标识为一个切面供容器读取




import com.thechenfan.utils.RedisUtils;
import com.thechenfan.utils.RequestHolder;
import com.thechenfan.utils.Response;
import com.thechenfan.utils.ResponseCode;
import lombok.extern.slf4j.Slf4j;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description //TODO 查询每次接口调用时userToken的准确性
 **/
@Aspect
@Order(1)
@Component
@Slf4j
public class QueryUserTokenAspect {
    @Autowired
    WxAccountRepository wxAccountRepository;

    @Autowired
    private RedisUtils redisUtils;


    @Pointcut("execution(* com.xxxx.controller.*.*(..)) " +
            "&& (!execution(* com.xxxx.LoginCtl.*(..)))"
    )
    public void mysql() {
    }

    @Pointcut("execution(* com.xxxx.controller.*.*(..))" +
            "&& (!execution(* com.xxxx.download(..)))"
    )
    public void clickHouse() {
    }

    @Around("clickHouse()")
    public Object beforeInvoke1(ProceedingJoinPoint joinPoint) {
        log.info("======>>>Aop切面clickHouse");
        return ever(joinPoint);
    }

    @Around("mysql()")
    public Object beforeInvoke(ProceedingJoinPoint joinPoint) {
        log.info("======>>>Aop切面mysql");
        return ever(joinPoint);
    }

    public Object ever(ProceedingJoinPoint joinPoint) {
        try {
            HttpServletRequest request = RequestHolder.getHttpServletRequest();
            /**
            * 自己的处理逻辑
            * */
            //执行方法
            log.info("切面执行成功!!!返回前端数据");
            Object result = joinPoint.proceed();
            return result;
        } catch (Throwable throwable) {
            log.error(throwable.getMessage(), throwable);
        }
        return null;
    }



}

其中可对整个类进行拦截,也可对整个类中的一个接口进行开放。自行设置。

 

其中有使用lombok插件注解的日志打印

   <!--lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐