この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:3
ページ更新者:guest
更新日時:2018-07-30 02:41:01

タイトル: AOPの使用方法とログ出力

本稿ではSpring FrameworkにおけるAOP(Acpect Oriented Programming)の使用方法を説明します。

また、実践的で非常に便利なログ出力方法の説明も併せてします。

 

AOPとは

AOPとは共通的な処理をAOPクラスにまとめて、あるクラスの特定のメソッドの開始前や開始後にその共通的な処理を実行させることが出来る仕組みです。

 

AOPのライブラリをpom.xmlに記述する

AOPを使用するためにはライブラリが必要です。

以下を参考にpom.xmlに記載してビルドしましょう。※Spring Bootでない場合。Spring Bootの場合は後述。

<!-- AOP -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>
spring-aop</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>
aspectjweaver</artifactId>
    <version>1.8.13</version>
</dependency>
<dependency>
    <groupId>cglib</groupId>
        <artifactId>
cglib</artifactId>
        <version>3.2.6</version>
</dependency>

※注意※ spring-aopのバージョンを3.1以上にすると「AnnotationAwareAspectJAutoProxyCreator」が見つからないエラーが発生する。情報求む。

 

Spring Bootの場合は以下の記述のみでOK。

<!-- AOP -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-aop</artifactId>

</dependency>


 

AOPを使用する宣言

※Spring Bootの場合は不要

いくつか方法があるが、シンプルなものを紹介。

適当なコンフィグクラスを作成して以下の内容を記述する。

@Configuration
@ComponentScan("com.example.springmvc")
@EnableAspectJAutoProxy

public class AppConfig {

}

※@ComponentScanのパッケージ名は環境に合わせてください。

 

AOPクラスの作成

@Aspectアノテーションを付与すればAOPのクラスとして認識される。

今回は実践的なログ出力方法を記述する。

@Aspect
@Component
public class TestAOP {

    @Before("execution(* com.example.springmvc2.*.*(..))")
    public void before(JoinPoint joinPoint) {
        System.out.println("Method Start:"  +
joinPoint.getSignature());
    }

    @After("execution(* com.example.springmvc2.*.*(..))")
    public void after(JoinPoint joinPoint) {
        System.out.println("Method End:"  +
joinPoint.getSignature());
    }
}

@Beforeはメソッドが実行される前に処理を実行する。

@Afterはメソッドが実行された後に処理を実行する。

executeはAOPを実行する条件を指定できる。※詳しくは後述

JoinPointクラスのgetSignatureメソッドを使用すると、実行したメソッドのオブジェクト情報が取得できる。

適当な本処理のメソッドを実行した際の出力結果は以下の通り。

Method Start:String com.example.springmvc2.HomeController.home(Locale,Model)

本処理

Method End:String com.example.springmvc2.HomeController.home(Locale,Model)

 

AOPクラスに付与するアノテーション一覧

@Before:メソッドの実行前に処理を実行する。

@After:メソッドの実行後に処理を実行する。

@AfterReturning:メソッドの実行後に処理を実行する。(正常終了した場合のみ)

@AfterThrowing:例外がスローされた場合のみ処理を実行する。

@Around:メソッドの実行タイミングを自分で指定し、前後に処理を記述する。
 

executeの条件指定

execute内の記述でAOPの起動条件を指定できる。

@Before("execution(* com.example.springmvc2.*.*(..))")

左から順に、

戻り値の型、パッケージ、クラス名、メソッド名、メソッド引数

となる。

*はワイルドカード。

※executeの例をもう少し具体的に記載するべし。どなたかよろしくお願いします。