简单两步,spring aop上手即用即会
生活随笔
收集整理的這篇文章主要介紹了
简单两步,spring aop上手即用即会
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
面向切面思想在于它的干凈,對(duì)邏輯代碼沒有任何侵入性,只需要在想要切入的方法或者類之上加上自定義的注解即可。
首先,就是自定義一個(gè)注解:
//這里我們定義一個(gè)名為 @MyPointer 的注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})//只能在方法上使用此注解
public @interface MyPointer{}
定義好一個(gè)注解之后呢,我們就可以定義我們這里的切點(diǎn)類
這里呢,我羅列一下我們常用的切面方法:
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
不同的方法有不同的參數(shù),比如下面的@AfterThrowing有一個(gè)throwing="e"的參數(shù),傳過來的就是我們切入的方法的報(bào)錯(cuò)信息。
而@AfterReturning會(huì)有一個(gè)returning="res"的參數(shù),是方法的返回值。
接下來上代碼:
@Aspect
@Component
@Slf4j
public class ModelViewAspect {//設(shè)置切入點(diǎn):這里直接攔截被@MyPointer注解的方法@Pointcut("@annotation(com.XXX.XXX.MyPointer)")public void pointcut() { }/*** 當(dāng)有MyPointer的注解的方法拋出異常的時(shí)候,做如下的處理*/@AfterThrowing(pointcut="pointcut()",throwing="e")public void afterThrowable(Throwable e) {log.error("切面發(fā)生了異常:", e);if(e instanceof CustomException){throw ModelViewException.transfer((CustomException) e);}}
}
接下來只需要將定義好的注解放在你要切入的程序的位置即可。
@MyPointer
@GetMapping("/hallo")
public String index(Model model) {return model;
}
以上!
總結(jié)
以上是生活随笔為你收集整理的简单两步,spring aop上手即用即会的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: plsql配置多数据源,想换哪个换哪个
- 下一篇: 手动将jar包导入pom依赖,让jar包