AOP的注解方式的实现

1.定义一个注解类

package org.example.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 *  切面
 *    切入点和通知的抽象
 *    定义   切入点和通知
 *    切入点:定义拦截哪些类和哪些方法
 *    通知:拦截之后 方法需要做什么
 */

@Component  //交给IOC容器并进行实例化

public class Laop01 {
    /**
     * 切入点:声明需要拦截那些类以及那些方法
     *    匹配规则;拦截哪些方法
     *    定义切入点 @Pointcut("匹配规则")
     *    Aop切入点表达式:
     *       1.执行所有的公共方法
     *            execution(public *(..))
     *       2.执行任意的set方法
     *            execution(* set*(..))
     *       3.设置指定包下的任意类的任意方法
     *            execution(* org.example.Service.*.*(..))
     *       4.设置指定包以及子包下的任意类 任意方法
     *            execution(* org.example.Service..*.*(..))
     *   表达式中的第一个*
     *      代表的是方法的修饰范围   (public private proteced)
     *      如果取值是*,则表示所有范围
     */
    public void cut(){

    }

    /**
    * 目标类中的方法执行前,此方法进行执行
    * */

    public void before(){
        System.out.println("这是一个前置通知");
    }

    /**
     * 最终通知   有无异常都会通知
     * */

    public void after(){
        System.out.println("这是一个后置通知。。。。");
    }

    /**
     * 目标类中方法无异常
     * */

    public void afterReturn(){
        System.out.println("这是一个返回通知。。。");
    }

    /**
     * 目标类中方法异常时会通知
     * */

    public void afterThrow(Exception e){
        System.out.println("异常通知");
    }


    public Object around(ProceedingJoinPoint pjp){
        System.out.println("环绕通知-前置通知");
        Object obj=null;
        try{
            //调用显式方法
            obj=pjp.proceed();
            System.out.println(pjp.getTarget());
            System.out.println("环绕通知-返回通知");
        }catch (Throwable throwable){
            throwable.printStackTrace();
            System.out.println("环绕通知-异常通知");

        }
        System.out.println("环绕通知-最终通知");
        return obj;
    }

}

2.XML中的配置信息

<aop:config>
        <aop:aspect ref="laop01">
            <!--定义一个切入点-->
            <aop:pointcut id="cut" expression="execution(* org.example.Service.*.*(..))"/>
            <aop:before method="before" pointcut-ref="cut"/>
            <aop:after method="after" pointcut-ref="cut"/>
            <aop:after-returning method="afterReturn" pointcut-ref="cut"/>
            <aop:after-throwing method="afterThrow" pointcut-ref="cut" throwing="e"/>
            <aop:around method="around" pointcut-ref="cut"/>
        </aop:aspect>
    </aop:config>
全部评论

相关推荐

昨天 18:44
已编辑
中山职业技术学院 Java
投递文远知行等公司7个岗位
点赞 评论 收藏
分享
水墨不写bug:疑似没有上过大学
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务