一部のメソッドを実行する前に論理的な判断をしたい、
もともとはインターセプターを使ってインターセプトしたかったのですが、それが分からないと言いました。
AOPのプリエンハンスメントとカスタム例外およびカスタム例外キャプチャを使用すると、この問題を解決できると思いました。
一度にたくさん使ったので、ぼんやりしたものを手に取りたい
1.最初にメモをカスタマイズします
1 / ** 2 * @program:四郎-デモ 3 * @description:自定义注解 4 * @author :@DogElder 5 * @Create:2020年4月18日20時42分 6 * * / 7 8 @Target( ElementType.METHOD) 9 @Retention(RetentionPolicy.RUNTIME) 10 public @ interface TestAnnotation { 11 }
2.例外クラスをカスタマイズする
最初にAOP依存関係をインポートする必要があります
1 <! - AOP - > 2 < 依存性> 3 < のgroupId > org.springframework.boot </ groupIdを> 4 < たartifactId >ばねブートスタータAOP </ たartifactId > 5 </ 依存>
1 インポートlombok.Data; 2 。3 / ** 4 * @program:シロ-デモ 。5 * @description:カスタム例外クラス 。6 * @author :@DogElder 。7 * @Create:2020年4月18日午前21時11分 8。* RuntimeException 9 を継承するには * * / 10 @Data 11 public class TestExcption extends RuntimeException { 12 13 private String code; 14 private String message; 15 16 // この場所はパラメータ化された構造を記述する必要があります17 public TestExcption(String code、String message){ 18 this .code = code; 19 this .message = message; 20 } 21 }
例外キャッチ
1 / ** 2 * @program:shiro-demo 3 * @description:异常处理 4 * @author :@DogElder 5 * @create:2020-04-18 21:20 6 * * / 7 @RestControllerAdvice 8 パブリック クラスTestExceptionHandler { 9 10 11 / ** 12 * @description:异常捕获 13 * @Param:java.util.Map <java.lang.Stringで、java.lang.Objectの> 14 * @return :java.util.Map < java.lang.String、java.lang.Object> 15 * @Author:@Dog_Elder 16 * @Date:2020年4月18日 17 * / 18 @ExceptionHandler(TestExcption クラス) 19 パブリックマップの<string、オブジェクト> handleCustomException(TestExcption customException){ 20 地図の<string、オブジェクト>誤差= 新規 HashMapの<> (); 21 error.put( "code" 、customException.getCode()); 22 error.put( "message" 、customException.getMessage()); 23 戻りエラー。 24 } 25 } 26
3. 次に、ファセットクラスをカスタマイズします
1 / ** 2 * @program:shiro-demo 3 * @description:カスタムアスペクト 4 * @author :@DogElder 5 * @create:2020-04-18 20:49 6 * * / 7 @Configuration 8 @Aspect 9 パブリック クラスTestAop { 10 11 12である/ ** 13は、 ポイントカットを宣言* @description 14 * @Param:ボイド 15 * @return :ボイド 16 * @author:@Dog_Elder 。17 * @date:2020年4月18日 18 * @Pointcutは、ポイントカットパラメータをポイントカット式として宣言します 19 *注:ここでのポイントカットは、@ annotationアノテーションクラスの完全な名前です(宣言したポイントカットが置き換えられる場所を参照してください) 20 * / 21 @Pointcut "@Annotation(com.shiro.shiro_demo.config.annotation.TestAnnotation)" ) 22が 公共 ボイド(testPointCut){ 23である 24 } 25 26である/ ** 27 * @description:DECLARE前部補強 28 * @Param。 void 29 * @return :void 30 * @Author:@Dog_Elder 31 * @Date:2020/4/18 32 * @Before事前拡張パラメーターはポイントカットメソッド 33 *注:throw exception throw exception throws throws RuntimeException and throw 34 * 35 * / 36 @Before( "testPointCut()" ) 37 public void testBefore()throws RuntimeException { 38 // ここにロジックコードを実装できます( demo) 39 // 簡単な例を記述します 40 int n = 1 ; 41 if(n!= 0 ){ 42 // この場所は、私たちが書いたカスタム例外です 43 throw new TestExcption( "401"、 「許可なし」); 44 } 45 } 46 47 }
テスト中
終わり