AOPを使ったログ出力のテスト。
対象パッケージの指定方法が複雑だが、それ以外はそれほど難しくはない。
概要
org.springframework.boot:spring-boot-starter-aop
をビルド定義ファイルに追加- AOPを使うクラスに@Aspectを付加
- メソッド実行前後に実行するメソッドにそれぞれ
@Before
および@After
アノテーションを付加
実装
springboot-study/aop-logging-test at master · orimajp/springboot-study
コントローラ(ログ出力対象クラス)
package com.example.aoploggingtest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TopController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index () {
return "ok";
}
}
ログコンフィグクラス
@Before
および@After
アノテーションのパラメータ指定方法が難しい。
package com.example.aoploggingtest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.util.logging.Logger;
@Aspect
@Component
public class LoggerConfig {
private final Logger logger = Logger.getLogger(getClass().getName());
@Before("execution(* com.example.aoploggingtest.*.*(..))")
public void invokeBefore(JoinPoint joinPoint) {
logger.info(String.format("START **** %s.%s", joinPoint.getTarget().getClass().toString(), joinPoint.getSignature().getName()));
}
@After("execution(* com.example.aoploggingtest.*.*(..))")
public void invokeAfter(JoinPoint joinPoint) {
logger.info(String.format("END **** %s.%s", joinPoint.getTarget().getClass().toString(), joinPoint.getSignature().getName()));
}
}
動作結果
2017-11-30 21:42:04.842 INFO 94906 --- [nio-8080-exec-2] com.example.aoploggingtest.LoggerConfig : START **** class com.example.aoploggingtest.TopController.index
2017-11-30 21:42:04.843 INFO 94906 --- [nio-8080-exec-2] com.example.aoploggingtest.LoggerConfig : END **** class com.example.aoploggingtest.TopController.index