Springboot+自定義注解+自定義AOP前置增強+自定義異常+自定義異常捕獲


開篇

想要在一些方法執行之前要進行一個邏輯判斷,

本來想使用攔截器來進行攔截但是后來還是說聲算了.

想到使用AOP的前置增強自定義異常自定義異常捕獲可以解決這個問題,

一次性用了這么多,就是想把之前比較模糊的東西重新拿起來

1.我們先自定義一個注解

 /**
  * @program: shiro-demo
  * @description: 自定義注解
  * @author: @DogElder
  * @create: 2020-04-18 20:42
  **/
  @Target(ElementType.METHOD)
 @Retention(RetentionPolicy.RUNTIME)
 public @interface TestAnnotation {
 }

 

2.自定義一個異常類

  我們首先要先導入AOP依賴

1 <!--aop-->
2 <dependency>
3     <groupId>org.springframework.boot</groupId>
4     <artifactId>spring-boot-starter-aop</artifactId>
5 </dependency>

 

 import lombok.Data;
  /**
  * @program: shiro-demo
  * @description: 自定義異常類
  * @author: @DogElder
  * @create: 2020-04-18 21:11
  * 要繼承RuntimeException
  **/
 @Data
 public class TestExcption extends RuntimeException {
     
     private String code;
     private String message;
     
 //    這個地方需要寫一個有參構造
     public TestExcption(String code, String message) {
         this.code = code;
         this.message = message;
     }
 }

 

異常捕獲

/**
  * @program: shiro-demo
  * @description: 異常處理
  * @author: @DogElder
  * @create: 2020-04-18 21:20
  **/
 @RestControllerAdvice
 public class TestExceptionHandler {
       /**
    * @Description: 異常捕獲
     * @Param: java.util.Map<java.lang.String,java.lang.Object>
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @Author:@Dog_Elder
     * @Date: 2020/4/18
     */
     @ExceptionHandler(TestExcption.class)
     public Map<String, Object> handleCustomException(TestExcption customException) {
         Map<String, Object> error = new HashMap<>();
         error.put("code", customException.getCode());
         error.put("message", customException.getMessage());
         return error;
     }
 }

 

 

3.然后我們自定義一個切面類

 /**
  * @program: shiro-demo
  * @description: 自定義切面
  * @author: @DogElder
  * @create: 2020-04-18 20:49
  **/
@Configuration
 @Aspect
 public class TestAop {
      
     /**
      * @Description: 聲明一個切入點
      * @Param: void
      * @return: void
      * @Author:@Dog_Elder
      * @Date: 2020/4/18
      * @Pointcut 聲明一個切入點 參數為切點表達式
     * 注意: 這里的切入點是@annotation注解類的全路名 (看你們聲明的切入點是在那里進行更換)
      */
     @Pointcut("@annotation(com.shiro.shiro_demo.config.annotation.TestAnnotation)")
     public void testPointCut() {
      }
      /**
     * @Description: 聲明一個前置增強
     * @Param: void
      * @return: void
      * @Author:@Dog_Elder
      * @Date: 2020/4/18
      * @Before 前置增強 參數為切點方法
      * 注意:拋異常 拋異常 拋異常 throws RuntimeException   和 throw
      *
      */
     @Before("testPointCut()")
     public void testBefore() throws RuntimeException{
 //        這里可以實現你的邏輯代碼 (因為是demo)
 //        我就寫一個簡單的小例子
         int n=1;
         if (n!=0) {
             //這個地方就是我們寫的自定義的異常
            throw  new TestExcption("401","無權限");
         }
     }
     
 }

 

測試

 

 

 

END


免責聲明!

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



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