SpringBoot快速上手异常集中处理&AOP切面编程&(自用)

SpringBoot——错误集中处理

简介:简化复杂的判断,通过抛出异常集中处理。降低耦合性


基础操作

  1. 创建错误

  2. 捕获错误

    @RestControllerAdvice
    public class ExceptionConfig {
    
        //捕获对应错误
        @ExceptionHandler(TryException.class)
        public void tryException(TryException exception){
            //对错误进行相应的处理
            System.out.println(exception.getMessage());
        }
    
    }
    

特点

  1. 可以注入
  2. 捕获父类就可以捕获子类

SpringBoot——AOP切面

简介:对于请求有拦截器,对于方法有AOP。AOP切面编程,游离于主逻辑的操作,通过对方法的侵入做到对方法的执行前后、错误、整个执行流程进行增强、修改操作。

专有名词

  • Aspect:切面,专门定义AOP的一个类。【给一个范围建立城墙】
  • Pointcut:切入点。【看守大门的士兵】
  • weave:织入。【安排看守大门的士兵去大门看守】
  • JointPoint:连接点。【被拦在大门的行人】
  • Advice:通知,对切入点进行增强处理【对拦截的人进行一些检查处理】
    • Before:前置增强
    • After:后置增强
    • AfterReturning:后置增强,带返回参数,遇到错误不执行
    • AfterThrowing:后置异常增强
    • Around:前后置增强

基础操作

  1. 导入对应依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    
  2. 创建切面

    @Aspect
    @Configuration
    public class AOPConfig {
        
    	//切入点
        @Pointcut("execution(* com.musir.problem.webLearn.controller.*.*(..))")
        public void pointCut(){}
    
        //前置
        @Before("pointCut()")
        public void before(JoinPoint joinPoint){}
    
        //正常后置
        @AfterReturning(value = "pointCut()",returning = "result")
        public void after(JoinPoint joinPoint,Object result){ }
    
        //错误后置
        @AfterThrowing(value = "pointCut()",throwing = "exception")
        public void error(JoinPoint joinPoint,NullPointerException exception){}
    
        //后置
        @After("pointCut()")
        public void end(JoinPoint joinPoint){}
    }
    
    1. execution:匹配公式

      • 作用:对方法进行匹配
      • 格式:execution(返回类型 返回参数 包.方法(参数..))
        • 返回类型和返回参数可以用 * 表示匹配任何类型
        • 参数通过 .. 表示长度与类型任意
    2. @Aspect:定义一个切面

    3. @Pointcut:定义一个切入点

      • 参数:匹配公式
    4. @Before:前置增强

      • 参数:匹配公式或切入点
    5. @AfterReturning:正常后置

      • 参数:
        • value:匹配公式或切入点【必须在第一个】
        • returning:绑定当前方法参数名称【当前AOP增强方法的返回值名称】
    6. @AfterThrowing:错误后置

      • 参数:
        • value:匹配公式或切入点【必须在第一个】
        • throwing:绑定当前错误参数名称【当前AOP增强方法的返回值名称】
    7. @After:后置

      • 参数:匹配公式或切入点
    8. JoinPoint:连接电

      • 常用方法:

        joinPoint.getArgs(): 获取请求参数即数组
        joinPoint.getSignature():
        	tostring(): 获取参数完整信息,如 string com.XX(String)
        	getName(): 获取方法名
        	getDeclaringTypeName(): 获取完整的方法路径
        

特点:

  1. 可以通过@Autowired注入,然后进行操作
  2. 操作时抛出错误依然会被集中处理
  3. 拦截的地方为获取参数之后,所以通过@RequestParm赋默认值是可以注入的

高级操作

通过注解执行

@Pointcut(value = "@annotation(com.hanna.common.lang.TokenAop)")
public void pointCut(){}

//获取注解参数
@Before("pointCut && @annotation(abc)" , returning = "result")
public void test(TokenAop abc,Object result){}//注意注解的annotation括号内参数与方法的参数名称相同
posted @ 2022-06-01 18:00  Ch1ee  阅读(398)  评论(0)    收藏  举报