1. 程式人生 > >10. Spring 面向切面

10. Spring 面向切面

rod cut CA end row execute urn code ID

10.1 產品清單概述

  • 通知(Advice)
    • 前置通知(Before)
    • 後置通知(After)
    • 返回通知(After-returning)
    • 異常通知(After-throwing)
    • 環繞通知(Around)
  • 連接點(Join point)
  • 切點(Poincut)
  • 切面(Aspect)
  • 引入(Introduction)
  • 織入(Weaving)
    • 編譯期
    • 類加載期
    • 運行期

10.1 @Aspect定義切面、定義切入位置

import org.aspectj.lang.annotation.*;

@Aspect
public class Notifier {
    @Before("execution(static void *..*.main(String[]))")
    
public void before(){ System.out.println("Application is running!"); } @After("execution(static void *..*.main(String[]))") public void after(){ System.out.println("execute end!"); } @AfterReturning("execution(static void *..*.main(String[]))") public void afterReturning(){ System.out.println(
"return end!"); } @AfterThrowing("execution(static void *..*.main(String[]))") public void afterThrowing(){ System.out.println("Exception"); } }

10.2 使用PointCup定義切入點、重復使用切入點

import org.aspectj.lang.annotation.*;

@Aspect
public class Notifier {

    @Pointcut("execution(static void *..*.main(String[]))")
    
public void pointCup(){} @Before("pointCup()") public void before(){ System.out.println("Application is running!"); } @After("pointCup()") public void after(){ System.out.println("execute end!"); } @AfterReturning("pointCup()") public void afterReturning(){ System.out.println("return end!"); } @AfterThrowing("pointCup()") public void afterThrowing(){ System.out.println("Exception"); } }

10. Spring 面向切面