簡單兩步,spring aop上手即用即會

面向切面思想在於它的乾淨,對邏輯代碼沒有任何侵入性,只需要在想要切入的方法或者類之上加上自定義的註解即可。
首先,就是自定義一個註解:

//這裏我們定義一個名爲 @MyPointer 的註解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})//只能在方法上使用此註解
public @interface MyPointer{

}
定義好一個註解之後呢,我們就可以定義我們這裏的切點類

這裏呢,我羅列一下我們常用的切面方法:

Before(前)  org.apringframework.aop.MethodBeforeAdvice 
After-returning(返回後) org.springframework.aop.AfterReturningAdvice 
After-throwing(拋出後) org.springframework.aop.ThrowsAdvice 
Arround(周圍) org.aopaliance.intercept.MethodInterceptor 
Introduction(引入) org.springframework.aop.IntroductionInterceptor 

不同的方法有不同的參數,比如下面的@AfterThrowing有一個throwing="e"的參數,傳過來的就是我們切入的方法的報錯信息。
而@AfterReturning會有一個returning="res"的參數,是方法的返回值。
接下來上代碼:

@Aspect
@Component
@Slf4j
public class ModelViewAspect {
    
    //設置切入點:這裏直接攔截被@MyPointer註解的方法
    @Pointcut("@annotation(com.XXX.XXX.MyPointer)")
    public void pointcut() { }
    
    /**
     * 當有MyPointer的註解的方法拋出異常的時候,做如下的處理
     */
    @AfterThrowing(pointcut="pointcut()",throwing="e")
    public void afterThrowable(Throwable e) {
        log.error("切面發生了異常:", e);
        if(e instanceof  CustomException){
            throw ModelViewException.transfer((CustomException) e);
        }
    }
}

接下來只需要將定義好的註解放在你要切入的程序的位置即可。


@MyPointer
@GetMapping("/hallo")
public String index(Model model) {
   
    return model;
}

以上!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章