Spring Pointcut 切面表達式

原文鏈接:https://www.jianshu.com/p/fbbdebf200c9

轉自:https://www.jianshu.com/p/fbbdebf200c9

 

Wildcard

  • *: 匹配任意數量的字符
  • +:匹配製定數量的類及其子類
  • ..:一般用於匹配任意數量的子包或參數
    詳細示例見後面的例子

Operators

  • &&:與操作符
  • ||:或操作符
  • !:非操作符

Designators

1. within()

//匹配productService類中的所有方法
@pointcut("within(com.sample.service.productService)")
public void matchType()

//匹配sample包及其子包下所有類的方法
@pointcut("within(com.sample..*)")
public void matchPackage()

2. 匹配對象(this, target, bean)

this(AType) means all join points where this instanceof AType is true. So this means that in your case once the call reaches any method of Service this instanceof Service will be true.

this(Atype)意思是連接所有this.instanceof(AType) == true的點,所以這意味着,this.instanceof(Service) 爲真的Service實例中的,所有方法被調用時。

target(AType) means all join points where anObject instanceof AType . If you are calling a method on an object and that object is an instanceof Service, that will be a valid joinpoint.

target(AType)意思是連接所有anObject.instanceof(AType)。如果你調用一個Object中的一個方法,且這個object是Service的實例,則這是一個合法的切點。
To summarize a different way - this(AType) is from a receivers perspective, and target(AType) is from a callers perspective.

總結:this(AType)同接受者方面描述,target(AType)則從調用者方面描述。

  • this
@pointcut("this(com.sample.demoDao)")
public void thisDemo()
  • target
@pointcut("target(com.sample.demoDao)")
public void targetDemo()
  • bean
//匹配所有以Service結尾的bean裏面的方法
@pointcut("bean(*Service)")
public void beanDemo

3. 參數匹配

  • bean
//匹配所有以find開頭,且只有一個Long類型參數的方法
@pointcut("execution(* *..find*(Long))")
public void argDemo1()

//匹配所有以find開頭,且第一個參數類型爲Long的方法
@pointcut("execution(* *..find*(Long, ..))")
public void argDemo2()
  • arg
@pointcut("arg(Long)")
public void argDemo3()

@pointcut("arg(Long, ..)")
public void argDemo4()

4. 匹配註解

  • @annotation
//匹配註解有AdminOnly註解的方法
@pointcut("@annotation(com.sample.security.AdminOnly)")
public void demo1()
  • @within
//匹配標註有admin的類中的方法,要求RetentionPolicy級別爲CLASS
@pointcut("@within(com.sample.annotation.admin)")
public void demo2()
  • @target
//註解標註有Repository的類中的方法,要求RetentionPolicy級別爲RUNTIME
@pointcut("target(org.springframework.stereotype.Repository)")
public void demo3()
  • @args
//匹配傳入參數的類標註有Repository註解的方法
@pointcut("args(org.springframework.stereotype.Repository)")
public void demo3()

5. execution()

格式:

execution(<修飾符模式>? <返回類型模式> <方法名模式>(<參數模式>) <異常模式>?)

標註❓的項目表示着可以省略

execution(
    modifier-pattern?  //修飾符
    ret-type-pattern  //返回類型
    declaring-type-pattern?  //方法模式
    name-pattern(param-pattern)  //參數模式
    throws-pattern?  //異常模式
)

/*
整個表達式可以分爲五個部分:

 1、execution(): 表達式主體。

 2、第一個*號:表示返回類型,*號表示所有的類型。

 3、包名:表示需要攔截的包名,後面的兩個句點表示當前包和當前包的所有子包,com.sample.service.impl包、子孫包下所有類的方法。

 4、第二個*號:表示類名,*號表示所有的類。

 5、*(..):最後這個星號表示方法名,*號表示所有的方法,後面括弧裏面表示方法的參數,兩個句點表示任何參數。
*/
@pointcut("execution(* com.sample.service.impl..*.*(..))")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章