この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:6
ページ更新者:guest
更新日時:2026-06-11 07:29:05

タイトル: AOPの使用方法
SEOタイトル: SpringにおけるAOPの使い方

この記事の要点
  • Spring AOP (Aspect Oriented Programming) の使い方
  • 共通処理(ログ・トランザクション等)をAspect クラスに集約し、対象メソッドの前後で実行
  • 必要ライブラリ: aspectjweaver + aspectjrt(Spring Boot は spring-boot-starter-aop 一括)
  • アノテーション: @Aspect(クラス)+ @Before / @After / @Around(メソッド)

 

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

 

AOPとは

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

 

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

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

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



    org.springframework
   
spring-aop
    3.1.4.RELEASE


    org.aspectj
   
aspectjweaver
    1.8.13


    cglib
       
cglib
        3.2.6

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

 

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

org.springframework.boot

spring-boot-starter-aop


 

AOPを使用する宣言

※Spring Bootの場合は不要

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

適当なコンフィグクラスを作成して以下の内容を記述する。(どこかしらのクラスでAOPを使用する宣言をする必要がある)

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@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の例をもう少し具体的に記載するべし。どなたかよろしくお願いします。