springBoot 自定义注解 + 自定义异常捕获实战

1.准备工作:需要一个正常的springBoot程序 和 添加一个注解相关的依赖

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

2.项目大致目录结构 由于项目用于商业就不提供全部源码了

 

 3.自定义注解类(为什么要这么定义 我也是抄的百度,能实现我想要的功能就行了)

package com.txj.bwbd.config.annotation;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidLogin {

    String value() default "";

}

4.aop逻辑处理

package com.txj.bwbd.config.annotation;

import cn.hutool.core.lang.Console;
import com.txj.bwbd.config.RequestFilter;
import com.txj.bwbd.config.exception.ValidExceptionException;
import com.txj.bwbd.constraint.CommonConstraint;
import com.txj.bwbd.sqlserver.entity.AccessToken;
import com.txj.bwbd.utils.TokenUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * 描述: 自定义登录后接口校验
 *
 * @author 官昌洪
 * @date 2020/4/2 15:42
 * @version V1.0
 */
@Aspect
@Component
public class ValidLoginAspect {

    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    RequestFilter requestFilter;

    public static final Logger logger = LoggerFactory.getLogger(ValidLoginAspect.class);


    @Pointcut("execution(@com.txj.bwbd.config.annotation.ValidLogin * *(..))")
    public void annotationPointcut() {
    }

    @Before("annotationPointcut()")
    public void beforePointcut(JoinPoint joinPoint) throws IOException {
        // 此处进入到方法前  可以实现一些业务逻辑
        Console.log("=========进入校验是否登录接口");
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        HttpServletResponse response = sra.getResponse();
        String tokenId = request.getHeader("tokenId");
        AccessToken accessToken = tokenUtil.obtainToken(tokenId);
        if (null != accessToken) {
            tokenUtil.setToken(accessToken);
        } else {
            throw new ValidExceptionException(CommonConstraint.REQUEST_UN_LOGIN_CODE, CommonConstraint.REQUEST_UN_LOGIN_MSG);
        }

    }

    @Around("annotationPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        return joinPoint.proceed();
    }

    /**
     * 在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
     * @param joinPoint
     */
    @AfterReturning("annotationPointcut()")
    public void doAfterReturning(JoinPoint joinPoint) {
    }

    private void checkToken(String token) {

    }

}

其实上面已经可以实现将注解放到我们的方法上会执行aop配置里面的逻辑了,后面是自定义异常处理

package com.txj.bwbd.config.exception;

import lombok.Data;

/**
 * 自定制异常类
 *
 * @author MoCha
 * @date 2019/5/25
 */
@Data
public class ValidExceptionException extends RuntimeException {
    private String code;
    private String message;

    public ValidExceptionException(String code, String message) {
        this.code = code;
        this.message = message;
    }
}
package com.txj.bwbd.config.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 描述: 全局异常处理
 *
 * @author 官昌洪
 * @date 2020/4/2 16:31
 * @version V1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(ValidExceptionException.class)
    public Map<String, Object> handleCustomException(ValidExceptionException customException) {
        Map<String, Object> errorResultMap = new HashMap<>(16);
        errorResultMap.put("code", customException.getCode());
        errorResultMap.put("message", customException.getMessage());
        return errorResultMap;
    }
}

ok 配置代码已经好了 我们来看下效果 在业务逻辑方法上添加我们的注解

@ValidLogin
    @RequestMapping("listYears")
    public List<Area> listYears(String contentType) {
        return iAreaService.listYears(contentType);
    }

执行我们aop里面逻辑 抛出自定义异常 嗨呀 soEasy

 

posted @ 2020-04-03 11:37  官萧何  阅读(3760)  评论(0编辑  收藏  举报