AspectJ介紹以及Pointcut註解應用
阿新 • • 發佈:2019-02-11
@AspectJ的風格類似純java註解的普通java類
Spring可以使用AspectJ來做切入點解析
AOP的執行時仍舊是純的Spring AOP,對AspectJ的編譯器或者織入無依賴性
@Aspect註解是不能夠通過類路徑自動檢測發現的,所以需要配合使用@Component註釋或者在xml配置bean
一個類中的@Aspect註解標識它為一個切面,並且將自己從自動代理中排除
@Pointcut註解,方法返回型別必須為void
Supported Pointcut Designators
execution 匹配方法執行的連線點
within 限定匹配特定型別的連線點
this 匹配特定連結點的bean引用是指定型別的例項的限制
target 限定匹配特點連結點的目標物件引數是指定型別的例項
args 限定匹配特點連結點的引數是給定型別的例項
@target 限定匹配特點連結點的類執行物件的具有給定型別的註解
@args 限定匹配特定連線點實際傳入引數的型別具有給定型別的註解
@within 限定匹配到內具有給定的註釋型別的連線點
@annotation 限定匹配特定連線點的主體具有給定的註解
示例
xml
Java<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.imooc.aop.aspectj"/> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
@Component
@Aspect
public class MoocAspect {
@Pointcut("execution(* com.imooc.aop.aspectj.biz.*Biz.*(..))")
public void pointcut() {}
@Pointcut("within(com.imooc.aop.aspectj.biz.*)")
public void bizPointcut() {}
}
定義良好的pointcuts
AspectJ是編譯期的AOP
檢查程式碼並匹配連線點與切入點的代價是昂貴的
一個好的切入點應該包括以下幾點:
選擇特定型別的連線點,如:execution,get,set,call,handler
確定連線點範圍,如:within,withcode
匹配上下文資訊,如:this,target,@annotation