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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM