Aspect Oriented Programming Java

2017/06/22

Aspect Oriented Programming Java

Spring BootのAOPについて記述する。

AOPとは?

Aspect Oriented Programming。

Spring AOP docs

※ Spring Bootアーキテクチャのサンプル


Aspect

Aspectは、Moduleとなる複数のクラス。

JoinPoint

JoinPointは、Advice箇所に挿入するクラス。

Advice

Adviceは、JoinPointを実行するクラス。

Before Advice

Adviceによって、JoinPointを実行するクラスの前のAdviceクラス。
事前に実行することができる。

After Advice

Adviceによって、JoinPointを実行するクラスの後のAdviceクラス。
事後に実行することができる。

After returning Advice

対象のメソッドの処理が正しく終了した場合にのみ実行されるAdviceクラス。
このAfterクラスによって、返り値をAdviceで利用可能にする。

After throwing advice

対象のメソッドの処理中に例外が発生した場合にのみ実行されるAdviceクラス。

Around advice

対象のメソッドの処理前や処理後など好きなタイミングで実行できるAdviceです。

PointCut

JoinPointの集合体。

Pointcut instruction Content Sample
within(~~~) ~~~のクラスに対して処理を行う。 within(com.sample.Controller)
execution(~~~) メソッドの実行。 execution(com.sample..(..))
target(~~~) 指定したクラスのインスタンスのメソッド呼び出しに適用。 target(com.sample.Parent)
args(~~~) 指定した引数の型にマッチするメソッド呼び出しに適用。 args(java.lang.String)
@annotation(~~~) 指定されたアノテーションが付与されたメソッド呼び出しに適用。 @annotation(org.springframework.stereotype.Component)

Spring AOP Annotations

Annotation Content Sample
@Before Before処理のIntercept @Before(“within(com.sample.Controller)”)
@After After処理のIntercept @After(“within(com.sample.Controller)”)
@Around Around処理のIntercept @Around(“within(com.sample.Controller)”)
@AfterReturning After処理の成功Intercept @AfterReturning(“within(com.sample.Controller)”)
@AfterThrowing After処理の失敗Intercept @AfterThrowing(“within(com.sample.Controller)”)

サンプルコード

build.gradleの設定。一部抜擢。

1
compile "org.springframework.boot:spring-boot-starter-aop"

RestControllerクラス。

1
2
3
4
5
6
7
8
@RestController
public class HelloController {

@RequestMapping(value = "/hello")
public String hello() {
return "Hello World!";
}
}

Aspectクラス。
サンプルとして、出力のSet処理を行う。

1
2
3
4
5
6
7
8
9
@Aspect
@Component
public class AspectLog {

@Before("within(com.sample.HelloController)")
public void before(JoinPoint joinPoint) {
System.out.println("Aspect test");
}
}