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

原文地址:https://www.cnblogs.com/guanxiaohe/p/12625467.html

时间: 2024-08-30 16:11:40

springBoot 自定义注解 + 自定义异常捕获实战的相关文章

SpringBoot利用自定义注解实现AOP

SpringBoot利用自定义注解实现AOP java 本文主要讲解利用SpringBoot的自定义注解来实现AOP思想. 在开始所有的操作之前,需要导入aop坐标: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> 如何自定义注解? 实际上注解本

Servlet3.0的注解自定义原生Listener监听器实战

简介:监听器介绍和Servlet3.0的注解自定义原生Listener监听器实战 自定义Listener(常用的监听器 servletContextListener.httpSessionListener.servletRequestListener) 代码示例: RequestListener.java 1 package net.xdclass.demo.listener; 2 3 import javax.servlet.ServletContextEvent; 4 import java

Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获

https://www.cnblogs.com/goloving/p/9142222.html 一.全局异常 1.首先创建异常处理包和类 2.使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获 package com.example.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.spri

SpringBoot入门十八,自定义注解的简单实现

项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用myEclipse新建一个SpringBoot项目即可,此示例springboot升级为2.2.1版本. 1. pom.xml添加aop支持 <!-- 引入aop切面支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-

springBoot AOP环绕增强、自定义注解、log4j2、MDC

(一)log4j2 maven配置 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <!-- 切换log4j2日志读取 --> <exclusion> <groupId>org.springframework.b

Springboot注解整理 二《自定义注解》

自定义注解 @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface CommonLog { String value() default ""; } @Target @Target 说明了Annotation所修饰的对象范围 取值ElementType 的类型如下所示: public enu

springboot通过AOP和自定义注解实现权限校验

自定义注解 PermissionCheck: package com.mgdd.sys.annotation; import java.lang.annotation.*; /** * @author LWW * @site www.lww.com * @company * @create 2019-12-16 14:08 */ // 标注这个类它可以标注的位置 @Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE}) // 标注这个注解

使用Java反射(Reflect)、自定义注解(Customer Annotation)生成简单SQL语句

这次给大家介绍一下在Java开发过程中 使用自定义注解开发:主要知识点:            1.反射            主要用于提取注解信息            2.自定义异常  主要是为了自己自定义一个异常信息            3.自定义注解  本次重点 学会如何自定义注解以及如何使用反射提取注解信息运用到实际开发下图表示在Java中注解的含义以及注解的分类和如何解析注解 通常我们使用自定义注解一般使用4中元注解即:@Target@Retention@Documented@In

(转)利用Spring AOP自定义注解解决日志和签名校验

一.需解决的问题 部分API有签名参数(signature),Passport首先对签名进行校验,校验通过才会执行实现方法. 第一种实现方式(Origin):在需要签名校验的接口里写校验的代码,例如: boolean isValid = accountService.validSignature(appid, signature, client_signature); if (!isValid) return ErrorUtil.buildError(ErrorUtil.ERR_CODE_COM