简单两步,spring aop上手即用即会
生活随笔
收集整理的這篇文章主要介紹了
简单两步,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;
}
以上!
總結
以上是生活随笔為你收集整理的简单两步,spring aop上手即用即会的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: plsql配置多数据源,想换哪个换哪个
- 下一篇: 手动将jar包导入pom依赖,让jar包