AOPとはAspect Oriented Programmingの頭文字をあてたもの。
ログの出力処理などの共通処理をアプリケーションの処理から分離する技術です。
元のアプリケーション処理に手を加えることなく処理を追加する事ができます。
AOPの用途は、ログ処理、トランザクション管理、認証チェックなどデバックに近い処理に用いられます。アプリケーション処理の様な重い処理には向いていません。
今回は、AOPの動きを確認するために、Controllerの処理の間にAOPでログを出す超簡単なプログラムを書きました。
Controller作成
htmlを用意するのが面倒くさいので、@RestControllerを使用します。
package com.example.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloAopController {
@RequestMapping("/test1")
public String input1() {
return "test1";
}
@RequestMapping("/test2")
public String input2() {
return "test2";
}
}
Aspect用クラスの作成
Aspectとは、Advice(ログ処理などが埋め込まれる処理)とJoinPoint(Adviceを埋め込む場所のこと)をまとめた名称になります。
Adviceの種類は、Before、After、Aroundなどがあります。
AdviceとJoinPoint参考サイト: https://qiita.com/ughirose/items/a7c66782f93cd1ae0d68
下記では、test1とtest2というURLにアクセスしたら、start endをコンソール上に表示する処理を加えています。
Aspectのポイントは、ポイントカットで実行対象のパッケージが細かく指定できることろです。
package com.example.demo;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class HelloAopLog {
// 注入したいデータを入れる
@Before("within(com.example.demo.HelloAopController)")
public void write1() {
System.out.println("start");
}
@After("within(com.example.demo.HelloAopController)")
public void write2() {
System.out.println("end");
}
}

