AOP(Aspect-oriented programming) 面向切面編程,是OOP的一個補充,這裏主要分析一下spring AOP技術。
先簡單說一下幾個基本概念:
1)target(目標類):就是需要被切入的類。
2)aspect(切面):主要是一個切面的功能模塊,由一些點以及圍繞這些點執行的動作完成的,比如日誌切面。
2.1)pointcut(切點):pointcut是應用待處理對象(某個類)添加功能的點。可以通過正則表達式匹配所有我們想要添加增加功能的點,例如某個類的某個方法、或者是某個註解被調用。
2.2)jointpoint(連接點):連接點是切面切入應用之後,動態獲取應用業務數據的對象(場所)。
2.3)advice(處理邏輯):advice是我們切面功能的實現,更關注與切面本身的功能和切入的時間點,目前Spring支持@Before、@Around、@After等具體處理邏輯添加點。
2.4)introduction:允許添加新的方法和屬性到類中,這個暫時還沒有用到。
7)proxy(代理類):被切入的類被重新代理的代理類。
8)weaving(插入):是指切面插入應用的方式。
結合具體業務詳細分析一下上面幾個概念:
target類:
@Service
public class DemoMethodService {
public void add(int i){
System.out.println("demoMethodService被調用");
}
}
aspect切面
@Aspect //1
@Component //2
public class LogAspect {
@Before("execution(* com.wisely.highlight_spring4.ch1.aop.DemoMethodService.*(..))") //6
public void before(JoinPoint joinPoint){
Object[] ar = joinPoint.getArgs();
for(int i=0;i<ar.length;i++) {
System.out.println(ar[i].toString());
}
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("before --方法規則式攔截,:"+method.getName());
}
}
測試代碼:
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AopConfig.class); //1
DemoMethodService demoMethodService = context.getBean(DemoMethodService.class);
demoMethodService.add(1);
context.close();
}
}
運行結果:
1
before --方法規則式攔截,:add
demoMethodService被調用