Spring日常笔记记录12--切点表达式的多种写法

AspectJ的切入点表达式

AspectJ定义了专门的表达式用于指定切入点。表达式原型是:

execution(modifiers-pattern? ret-type-pattern 
      declaring-type-pattern?name-pattern(param-pattern)
       throws-pattern?)

 

解释:

modifiers-pattern]   访问权限类型
ret-type-pattern   返回值类型
declaring-type-pattern   包名类名
name-pattern(param-pattern)   方法名(参数类型和参数个数)
throws-pattern   抛出异常类型
?  表示可选的部分
 
以上表达式共 4 个部分。
execution(访问权限 方法返回值 方法声明(参数) 异常类型)
 
        切入点表达式要匹配的对象就是目标方法的方法名。所以,execution 表达式中明显就
是方法的签名。注意,表达式中黑色文字表示可省略部分,各部分间用空格分开。在其中可
以使用以下符号:

 

 

举例:
execution(public * *(..))
指定切入点为:任意公共方法。
 
execution(* set*(..))
指定切入点为:任何一个以“set”开始的方法。
 
execution(* com.xyz.service.*.*(..))
指定切入点为:定义在 service 包里的任意类的任意方法。
 
execution(* com.xyz.service..*.*(..))
指定切入点为:定义在 service 包或者子包里的任意类的任意方法。“..”出现在类名中时,后面必须跟“*”,表示包、子包下的所有类。
 
execution(* *..service.*.*(..))
指定所有包下的 serivce 子包下所有类(接口)中所有方法为切入点 

 

代码演示:

 

package com.example.ba01;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import java.util.Date;

/**
 * @Aspect:是aspectj框架中的注解。
 *      作用:表示当前类是切面类。
 *      切面类:是用来给业务方法增加功能的类,在这个类中有切面的功能代码
 *      使用位置:在类定义的上面
 */
@Aspect
public class MyAspect {
    /**
     * 定义方法,方法是实现切面功能的
     * 方法的定义要求:
     * 1.公共方法public
     * 2.方法没有返回值
     * 3.方法名称自定义
     * 4.方法可以有参数,也可以没有参数
     *   如果有参数,参数不是自定义的,有几个参数类型可以使用
     */

    /**
     * @Before:前置通知注解
     *      属性:value,是切入点表达式,表示切面的功能执行的位置
     *      位置:在方法的上面
     *  特点:
     *  1.在目标方法之前先执行
     *  2.不会改变目标放方法的执行结果
     *  3.不会影响目标方法的执行
     *
     */
    /*@Before(value = "execution(public void com.example.ba01.SomeServiceImpl.doSome(String, Integer))")
    public void myBefore(){
        //就是你切面要执行的功能代码
        System.out.println("前置通知,切面功能:在目标方法之前输出执行时间:"+new Date());
    }*/

    /*@Before(value = "execution(void *..SomeServiceImpl.doSome(String, Integer))")
    public void myBefore(){
        //就是你切面要执行的功能代码
        System.out.println("1前置通知,切面功能:在目标方法之前输出执行时间:"+new Date());
    }*/

    /*@Before(value = "execution(void *..SomeServiceImpl.doSome(..))")
    public void myBefore(){
        //就是你切面要执行的功能代码
        System.out.println("2前置通知,切面功能:在目标方法之前输出执行时间:"+new Date());
    }*/

    /*@Before(value = "execution(void *..SomeServiceImpl.do*(..))")
    public void myBefore(){
        //就是你切面要执行的功能代码
        System.out.println("3前置通知,切面功能:在目标方法之前输出执行时间:"+new Date());
    }*/

    @Before(value = "execution(* *..SomeServiceImpl.do*(..))")
    public void myBefore(){
        //就是你切面要执行的功能代码
        System.out.println("4前置通知,切面功能:在目标方法之前输出执行时间:"+new Date());
    }

}

 

 

 

 

posted @ 2021-07-27 21:58  Brack_Pearl  阅读(201)  评论(0编辑  收藏  举报