1. 程式人生 > >註解@Aspect實現AOP功能

註解@Aspect實現AOP功能

res pointer tail bject nat obj 功能 目標 aslist

springboot中pom引入jar

<!-- aop 切面 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

要想把一個類變成切面類,需要兩步,
① 在類上使用 @Component 註解 把切面類加入到IOC容器中
② 在類上使用 @Aspect 註解 使之成為切面類

相關代碼

@Aspect
@Component
public class AspectTest {
    /**
     * 前置通知:目標方法執行之前執行以下方法體的內容
     * @param jp
     */
    @Before("execution(* com.springboot.aop.controller.*.*(..))")
    public void beforeMethod(JoinPoint jp){
        String methodName = jp.getSignature().getName();
        System.out.println(
"【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs())); } /** * 返回通知:目標方法正常執行完畢時執行以下代碼 * @param jp * @param result */ @AfterReturning(value="execution(* com.springboot.aop.controller.*.*(..))",returning="result") public void afterReturningMethod(JoinPoint jp, Object result){ String methodName
= jp.getSignature().getName(); System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】"); } /** * 後置通知:目標方法執行之後執行以下方法體的內容,不管是否發生異常。 * @param jp */ @After("execution(* com.springboot.aop.controller.*.*(..))") public void afterMethod(JoinPoint jp){ System.out.println("【後置通知】this is a afterMethod advice..."); } /** * 異常通知:目標方法發生異常的時候執行以下代碼 */ @AfterThrowing(value="execution(* com.springboot.aop.controller.*.*(..))",throwing="e") public void afterThorwingMethod(JoinPoint jp, NullPointerException e){ String methodName = jp.getSignature().getName(); System.out.println("【異常通知】the method 【" + methodName + "】 occurs exception: " + e); } /** * 環繞通知:目標方法執行前後分別執行一些代碼,發生異常的時候執行另外一些代碼 * @return */ @Around(value="execution(* com.springboot.aop.controller.*.*(..))") public Object aroundMethod(ProceedingJoinPoint jp){ String methodName = jp.getSignature().getName(); Object result = null; try { System.out.println("【環繞通知中的--->前置通知】:the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs())); //執行目標方法 result = jp.proceed(); System.out.println("【環繞通知中的--->返回通知】:the method 【" + methodName + "】 ends with " + result); } catch (Throwable e) { System.out.println("【環繞通知中的--->異常通知】:the method 【" + methodName + "】 occurs exception " + e); } System.out.println("【環繞通知中的--->後置通知】:-----------------end.----------------------"); return result; } }
作者:胖百二
來源:CSDN
原文:https://blog.csdn.net/wellxielong/article/details/80642726
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

註解@Aspect實現AOP功能