関数の開始と終了をログに出力する処理をAOPでやってみようと思い、Spring AOPを試してみました。
「Spring徹底入門」によるとSpring AOPを利用するために以下ライブラリが必要とのこと。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
上記説明を最初みたとき、「バージョンは不要?」と思ったけど、必要でした。
まあ、バージョンは日々変わるから<version>表記を省いたのでしょう。
で以下のバージョンを指定
※Spring MVCプロジェクト作成したとき、spring-contextはデフォルトで設定されているのでspring-aopとaspectjweaverを追加
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
Aspectクラスを実装
package jp.co.spring.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MethodAspect {
private static final Logger logger = LoggerFactory.getLogger(MethodAspect.class);
@Before("execution(* *..*Controller.*(..))")
public void startLog(JoinPoint jp) {
logger.info("========start: " + jp.getSignature() + " ==========");
}
}
servlet-context.xmlにAOP使用設定を追加
<aop>タグを使用するのでxmlns:aop="http://www.springframework.org/schema/aop" とxsi:schemaLocationの設定も要修正
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 中略 -->
<aop:aspectj-autoproxy />
これでTomcat起動して動作確認と思ったら何度やってもTomcatが起動しません。。
「重大: A child container failed during start」て出てなんだこれは~と思っていろいろ試してたらaspectjweaverのバージョンが1.8.9だとダメみたいでした。(原因は不明)
というわけでaspectjweaverのバージョンを一つ下げて1.8.8で試したら動きました。
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.8</version>
</dependency>