SpringのAOPのクイックスタート

高速春AOPの実装クラスを書きます

  1. トラフィッククラスが定義され、注釈は@Service春のコンテナを使用して追加しました。
@Service
public class MyService {
  public String print() {
    System.out.println("print...");
    return "End";
  }
}
  1. クラス定義部、注釈は、カットラベル@Aspectとして@Component Springコンテナを追加使用してクラスを表し、通知の種類を標識するための方法に関する。

    通知タイプ
    • アドバイスの前に
    • アドバイスを返送した後、
    • ニュースに戻ります
    • 異常の通知
    • アドバイスアラウンド
@Aspect
@Component
public class MyAspect {

  @Pointcut("execution(* com.xxx.MyService.*(..))")
  public void pointCut() {
  }

  @Before("pointCut()")
  public void start() {
    System.out.println("前置通知");
  }

  @After("pointCut()")
  public void end() {
    System.out.println("后置通知");
  }

  @AfterReturning("pointCut()")
  public void returnStart() {
    System.out.println("返回通知");
  }

  @AfterThrowing("pointCut()")
  public void exceptionStart() {
    System.out.println("异常通知");
  }

  @Around("pointCut()")
  public Object startAround(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("环绕通知开始");
    Object proceed = joinPoint.proceed(joinPoint.getArgs());
    System.out.println("环绕通知结束" + proceed);
    return proceed;
  }
}
  1. 起動クラスを定義します。
@EnableAspectJAutoProxy
@ComponentScan
public class App {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);

    MyService service = context.getBean(MyService.class);
    System.out.println("启动");
    String print = service.print();
    System.out.println(print);

  }
}

輸出

启动
环绕通知开始
前置通知
print...
环绕通知结束End
后置通知
返回通知
End

おすすめ

転載: www.cnblogs.com/bigshark/p/11318778.html