Springaop-quick-guide

提供:Dev Guides
移動先:案内検索

Spring AOP-概要

Spring Frameworkの主要なコンポーネントの1つは、* Aspect Oriented Programming(AOP)*フレームワークです。 アスペクト指向プログラミングでは、プログラムロジックを「いわゆる懸念事項」と呼ばれる別個の部分に分解する必要があります。 アプリケーションの複数のポイントにまたがる機能は、横断的関心事と呼ばれます。 これらの*横断的な関心事*は、アプリケーションのビジネスロジックと概念的に分離されています。 ロギング、監査、宣言的トランザクション、セキュリティ、キャッシングなどの側面のさまざまな一般的な良い例があります。

OOPのモジュール性の重要な単位はクラスですが、AOPのモジュール性の単位は側面です。 依存性注入は、アプリケーションオブジェクトを相互に分離するのに役立ちますが、AOPは、影響を受けるオブジェクトから横断的な関心事を分離するのに役立ちます。 AOPは、Perl、.NET、Javaなどのプログラミング言語のトリガーのようなものです。

Spring AOPモジュールにより、インターセプターはアプリケーションをインターセプトできます。 たとえば、メソッドの実行時に、メソッドの実行前または実行後に機能を追加できます。

link:/cgi-bin/printpage.cgi [__印刷]

Spring AOP-環境設定

この章では、WindowsおよびLinuxベースのシステムでSpring AOPを設定するプロセスについて説明します。 Spring AOPは、複雑なセットアップ手順なしでいくつかの簡単な手順を実行するだけで、現在のJava環境およびMAVENと簡単にインストールおよび統合できます。 インストール中にユーザー管理が必要です。

システム要求

JDK Java SE 2 JDK 1.5 or above
Memory 1 GB RAM (recommended)
Disk Space No minimum requirement
Operating System Version Windows XP or above, Linux

Spring AOPをインストールする手順を見てみましょう。

ステップ1:Javaインストールを確認する

まず、システムにJava Software Development Kit(SDK)をインストールする必要があります。 これを確認するには、作業しているプラ​​ットフォームに応じて、次の2つのコマンドのいずれかを実行します。

Javaインストールが適切に行われている場合、Javaインストールの現在のバージョンと仕様が表示されます。 サンプル出力を次の表に示します。

Platform Command Sample Output
Windows

Open command console and type −

  • \> java -version*

a

Javaバージョン「1.7.0_60」

Java(TM)SEランタイム環境(ビルド1.7.0_60-b19)

Java Hotspot(TM)64ビットサーバーVM(ビルド24.60-b09、混合モード)

Linux

Open command terminal and type −

  • $ java -version*

a

Javaバージョン "1.7.0_25"

JDKランタイム環境を開く(rhel-2.3.10.4.el6_4-x86_64)

JDK 64ビットサーバーVMを開く(ビルド23.7-b01、混合モード)

このチュートリアルの読者は、システムにJava SDKバージョン1.7.0_60がインストールされていることを前提としています。

Java SDKがない場合は、https://www.oracle.com/technetwork/java/javase/downloads/indexlから現在のバージョンをダウンロードし、インストールしてください。

ステップ2:Java環境を設定する

Javaがマシンにインストールされているベースディレクトリの場所を指すように、環境変数JAVA_HOMEを設定します。 例えば、

Sr.No. Platform & Description
1

Windows

JAVA_HOMEをC:\ ProgramFiles \ java \ jdk1.7.0_60に設定します

2

Linux

エクスポートJAVA_HOME =/usr/local/java-current

Javaコンパイラの場所の完全パスをシステムパスに追加します。

Sr.No. Platform & Description
1

Windows

文字列「C:\ Program Files \ Java \ jdk1.7.0_60 \ bin」をシステム変数Pathの最後に追加します。

2

Linux

エクスポートPATH = $ PATH:$ JAVA_HOME/bin/

上記で説明したように、コマンドプロンプトからコマンド java -version を実行します。

ステップ3:Mavenアーカイブをダウンロードする

[[1]] 3.3.3をダウンロードします

OS Archive Name
Windows apache-maven-3.3.3-bin.zip
Linux apache-maven-3.3.3-bin.tar.gz
Mac apache-maven-3.3.3-bin.tar.gz

ステップ4:Mavenアーカイブを抽出する

Maven 3.3.3をインストールするディレクトリにアーカイブを抽出します。 サブディレクトリapache-maven-3.3.3がアーカイブから作成されます。

OS Location (can be different based on your installation)
Windows C:\Program Files\Apache Software Foundation\apache-maven-3.3.3
Linux /usr/local/apache-maven
Mac /usr/local/apache-maven

ステップ5:Maven環境変数を設定する

M2_HOME、M2、MAVEN_OPTSを環境変数に追加します。

OS Output
Windows

Set the environment variables using system properties.

M2_HOME = C:\ Program Files \ Apache Software Foundation \ apache-maven-3.3.3

M2 =%M2_HOME%\ bin

MAVEN_OPTS = -Xms256m -Xmx512m

Linux

Open command terminal and set environment variables.

export M2_HOME =/usr/local/apache-maven/apache-maven-3.3.3

export M2 = $ M2_HOME/bin

export MAVEN_OPTS = -Xms256m -Xmx512m

Mac

Open command terminal and set environment variables.

export M2_HOME =/usr/local/apache-maven/apache-maven-3.3.3

export M2 = $ M2_HOME/bin

export MAVEN_OPTS = -Xms256m -Xmx512m

ステップ6:Maven Binディレクトリの場所をシステムパスに追加する

次に、システムパスにM2変数を追加します。

OS Output
Windows Append the string ;%M2% to the end of the system variable, Path.
Linux export PATH = $M2:$PATH
Mac export PATH = $M2:$PATH

ステップ7:Mavenのインストールを確認する

コンソールを開き、次の mvn コマンドを実行します。

OS Task Command
Windows Open Command Console c:\> mvn --version
Linux Open Command Terminal $ mvn --version
Mac Open Terminal machine:< joseph$ mvn --version

最後に、上記のコマンドの出力を確認します。これは次のようになります-

OS Output
Windows

Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T17:27:37+05:30)

Mavenホーム:C:\ Program Files \ Apache Software Foundation \ apache-maven-3.3.3

Javaバージョン:1.7.0_75、ベンダー:Oracle Corporation

Javaホーム:C:\ Program Files \ Java \ jdk1.7.0_75 \ jre

デフォルトロケール:en_US、プラットフォームエンコーディング:Cp1252

Linux

Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T17:27:37+05:30)

Mavenホーム:/usr/local/apache-maven/apache-maven-3.3.3

Javaバージョン:1.7.0_75、ベンダー:Oracle Corporation

Javaホーム:/usr/local/java-current/jdk1.7.0_75/jre

Mac

Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T17:27:37+05:30)

Mavenホーム:/usr/local/apache-maven/apache-maven-3.3.3

Javaバージョン:1.7.0_75、ベンダー:Oracle Corporation

Javaホーム:/Library/Java/Home/jdk1.7.0_75/jre

ステップ8-Eclipse IDEのセットアップ

このチュートリアルのすべての例は、Eclipse IDEを使用して作成されています。 そのため、最新バージョンのEclipseをマシンにインストールすることをお勧めします。

Eclipse IDEをインストールするには、https://www.eclipse.org/downloads/から最新のEclipseバイナリをダウンロードします。 インストールをダウンロードしたら、バイナリ配布物を便利な場所に解凍します。 たとえば、WindowsのC:\ eclipse、またはLinux/Unixの/usr/local/eclipseで、最後にPATH変数を適切に設定します。

Eclipseは、Windowsマシンで次のコマンドを実行することで開始できます。または、eclipse.exeをダブルクリックできます。

 %C:\eclipse\eclipse.exe

Eclipseは、Unix(Solaris、Linuxなど)マシンで次のコマンドを実行することで起動できます-

$/usr/local/eclipse/eclipse

正常に起動した後、すべてが正常であれば、次の結果が表示されます-

Eclipseホームページ

この最後の手順が完了したら、次の章で説明する最初のAOPの例に進む準備ができています。

Spring AOP-コアコンセプト

AOPの使用を開始する前に、AOPの概念と用語について理解しましょう。 これらの用語は、Springに固有のものではなく、AOPに関連しています。

Sr.No. Terms & Description
1

Aspect

横断的な要件を提供する一連のAPIを備えたモジュール。 たとえば、ロギングモジュールは、ロギングのAOPアスペクトと呼ばれます。 アプリケーションは、要件に応じて任意の数の側面を持つことができます。

2

Join point

これは、AOPアスペクトをプラグインできるアプリケーション内のポイントを表します。 また、Spring AOPフレームワークを使用してアクションが実行されるアプリケーション内の実際の場所であるとも言えます。

3

Advice

これは、メソッドの実行前または実行後に実行される実際のアクションです。 これは、Spring AOPフレームワークによるプログラム実行中に呼び出される実際のコードです。

4

PointCut

これは、アドバイスを実行する1つ以上のジョインポイントのセットです。 AOPの例で見るように、式またはパターンを使用してPointCutsを指定できます。

5

Introduction

導入により、新しいメソッドまたは属性を既存のクラスに追加できます。

6

Target object

1つ以上の側面によってアドバイスされているオブジェクト。 このオブジェクトは常にプロキシオブジェクトです。 推奨オブジェクトとも呼ばれます。

7

Weaving

ウィービングは、アスペクトを他のアプリケーションタイプまたはオブジェクトとリンクして、推奨オブジェクトを作成するプロセスです。 これは、コンパイル時、ロード時、または実行時に実行できます。

Spring AOP-アドバイスの種類

Springの側面は、次の表に示す5種類のアドバイスで機能します。

Sr.No. Advice & Description
1

before

メソッドを実行する前にアドバイスを実行してください。

2

after

結果に関係なく、メソッドの実行後にアドバイスを実行します。

3

after-returning

メソッドが正常に完了した場合にのみ、メソッドの実行後にアドバイスを実行します。

4

after-throwing

メソッドが例外をスローして終了した場合にのみ、メソッドの実行後にアドバイスを実行します。

5

around

アドバイスされたメソッドが呼び出される前後にアドバイスを実行します。

Spring AOP-実装

Springは、カスタムアスペクトを実装するために* @ AspectJアノテーションスタイル*アプローチと*スキーマベース*アプローチをサポートしています。

XMLスキーマベース

アスペクトは、XMLベースの構成とともに通常のクラスを使用して実装されます。

このセクションで説明されているAOP名前空間タグを使用するには、次のように説明されている春のAOPスキーマをインポートする必要があります-

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"

   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <!-- bean definition & AOP specific configuration -->

</beans>

アスペクトを宣言する

*aspect* は *<aop:aspect>* 要素を使用して宣言され、バッキングBeanは次のように *ref* 属性を使用して参照されます。
<aop:config>
   <aop:aspect id = "myAspect" ref = "aBean">
   ...
   </aop:aspect>
</aop:config>

<bean id = "aBean" class = "...">
   ...
</bean>

ここでは、前の章で見たように、他のSpring Beanと同じように「aBean」が構成され、依存関係が注入されます。

PointCutの宣言

*PointCut* は、結合ポイント(つまり、 メソッド)さまざまなアドバイスを使用して実行します。 XML Schemaベースの構成で作業中、PointCutは次のように定義されます-
<aop:config>
   <aop:aspect id = "myAspect" ref = "aBean">

   <aop:PointCut id = "businessService"
      expression = "execution(* com.xyz.myapp.service.*.*(..))"/>
      ...
   </aop:aspect>
</aop:config>

<bean id = "aBean" class = "...">
   ...
</bean>

次の例では、com.finddevguidesパッケージのStudentクラスで使用可能なgetName()メソッドの実行と一致する「businessService」という名前のPointCutを定義しています。

<aop:config>
   <aop:aspect id = "myAspect" ref = "aBean">

   <aop:PointCut id = "businessService"
      expression = "execution(* com.finddevguides.Student.getName(..))"/>
   ...
   </aop:aspect>
</aop:config>

<bean id = "aBean" class = "...">
   ...
</bean>

アドバイスの宣言

次のように<aop:\ {ADVICE NAME}>要素を使用して、<aop:aspect>内で5つのアドバイスのいずれかを宣言できます。

<aop:config>
   <aop:aspect id = "myAspect" ref = "aBean">
      <aop:PointCut id = "businessService"
         expression = "execution(* com.xyz.myapp.service.*.*(..))"/>

      <!-- a before advice definition -->
      <aop:before PointCut-ref = "businessService"
         method = "doRequiredTask"/>

      <!-- an after advice definition -->
      <aop:after PointCut-ref = "businessService"
         method = "doRequiredTask"/>

      <!-- an after-returning advice definition -->
      <!--The doRequiredTask method must have parameter named retVal -->
      <aop:after-returning PointCut-ref = "businessService"
         returning = "retVal"
         method = "doRequiredTask"/>

      <!-- an after-throwing advice definition -->
      <!--The doRequiredTask method must have parameter named ex -->
      <aop:after-throwing PointCut-ref = "businessService"
        throwing = "ex"
         method = "doRequiredTask"/>

      <!-- an around advice definition -->
      <aop:around PointCut-ref = "businessService"
         method = "doRequiredTask"/>
   ...
   </aop:aspect>
</aop:config>

<bean id = "aBean" class = "...">
   ...
</bean>

同じ doRequiredTask または異なるアドバイスに異なるメソッドを使用できます。 これらのメソッドは、アスペクトモジュールの一部として定義されます。

@AspectJベース

@AspectJは、アスペクトをJava 5アノテーションが付けられた通常のJavaクラスとして宣言するスタイルを指します。 @AspectJは、アスペクトをJava 5アノテーションが付けられた通常のJavaクラスとして宣言するスタイルを指します。 @AspectJサポートは、XMLスキーマベースの構成ファイル内に次の要素を含めることで有効になります。

<aop:aspectj-autoproxy/>

アスペクトを宣言する

アスペクトクラスは他の通常のBeanと同様であり、次のように@Aspectアノテーションが付けられることを除いて、他のクラスと同様にメソッドとフィールドを持つことができます。

package org.xyz;

import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AspectModule {

}

次のように、他のBeanと同様にXMLで構成されます。

<bean id = "myAspect" class = "org.xyz.AspectModule">
   <!-- configure properties of aspect here as normal -->
</bean>

PointCutの宣言

*PointCut* は、結合ポイント(つまり、 メソッド)さまざまなアドバイスを使用して実行します。 @AspectJベースの構成で作業中、PointCut宣言には2つの部分があります-
  • 対象のメソッド実行を正確に決定するPointCut式。
  • 名前と任意の数のパラメーターで構成されるPointCut署名。 メソッドの実際の本体は無関係であり、実際には空である必要があります。

次の例では、パッケージcom.xyz.myapp.serviceの下のクラスで使用可能なすべてのメソッドの実行に一致する「businessService」という名前のPointCutを定義します。

import org.aspectj.lang.annotation.PointCut;

@PointCut("execution(* com.xyz.myapp.service.*.*(..))")//expression
private void businessService() {} //signature

次の例では、パッケージcom.finddevguidesのStudentクラスで使用可能なgetName()メソッドの実行と一致する「getname」という名前のPointCutを定義しています。

import org.aspectj.lang.annotation.PointCut;

@PointCut("execution(* com.finddevguides.Student.getName(..))")
private void getname() {}

アドバイスの宣言

以下に示す@ \ {ADVICE-NAME}アノテーションを使用して、5つのアドバイスのいずれかを宣言できます。 これは、PointCut署名メソッドbusinessService()が既に定義されていることを前提としています。

@Before("businessService()")
public void doBeforeTask(){
   ...
}

@After("businessService()")
public void doAfterTask(){
   ...
}

@AfterReturning(PointCut = "businessService()", returning = "retVal")
public void doAfterReturnningTask(Object retVal){
  //you can intercept retVal here.
   ...
}

@AfterThrowing(PointCut = "businessService()", throwing = "ex")
public void doAfterThrowingTask(Exception ex){
  //you can intercept thrown exception here.
   ...
}

@Around("businessService()")
public void doAroundTask(){
   ...
}

任意のアドバイスに対してPointCutインラインを定義できます。 以下は、アドバイスの前にインラインPointCutを定義する例です。

@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
   ...
}

Spring AOP-XMLベースのアプリケーション

この章では、Spring AOP Frameworkを使用して実際のAOPアプリケーションを作成します。 Spring-WSフレームワークを使用して最初の例の記述を開始する前に、link:/springaop/springaop_environment [Spring Web Services-Environment Setup]の章で説明されているように、Spring AOP環境が適切に設定されていることを確認する必要があります。

次に、コンソールを使用した簡単なSpring AOPアプリケーションの作成に進み、AOPの概念を示します。

プロジェクトを作成する

ステップ1 *-コマンドコンソールを開き、C:\ MVNディレクトリに移動して、次の *mvn コマンドを実行します。

C:\MVN>mvn archetype:generate -DgroupId = com.finddevguides -DartifactId = Student
    -DarchetypeArtifactId = maven-archetype-quickstart -DinteractiveMode = false

Mavenは処理を開始し、完全なJavaアプリケーションプロジェクト構造を作成します。

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) > generate-sources
@ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.4:generate (default-cli) < generate-sources
@ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom --
-
[INFO] Generating project in Batch mode
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/ma
ven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/mav
en-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar (5 KB at 1.1 KB/s
ec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/ma
ven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/mav
en-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom (703 B at 1.2 KB/
sec)
[INFO] -------------------------------------------------------------------------
---
[INFO] Using following parameters for creating project from Old (1.x) Archetype:
 maven-archetype-quickstart:1.0
[INFO] -------------------------------------------------------------------------
---
[INFO] Parameter: groupId, Value: com.finddevguides
[INFO] Parameter: packageName, Value: com.finddevguides
[INFO] Parameter: package, Value: com.finddevguides
[INFO] Parameter: artifactId, Value: Student
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\Student
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:17 min
[INFO] Finished at: 2017-02-19T21:11:14+05:30
[INFO] Final Memory: 15M/114M
[INFO] ------------------------------------------------------------------------
  • ステップ2 *-C:/MVNディレクトリに移動します。 studentという名前の(artifactIdで指定された)Javaアプリケーションプロジェクトが作成されます。 POM.xmlを更新して、Spring-AOP依存関係を含めます。 MainApp.java、Student.java、およびLogging.javaファイルを追加します。
*POM.xml*
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>Student</artifactId>
   <packaging>jar</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>Student</name>
   <url>http://maven.apache.org</url>

   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aop</artifactId>
         <version>4.1.0.RELEASE</version>
      </dependency>

      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>4.1.4.RELEASE</version>
      </dependency>

      <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjweaver</artifactId>
         <version>1.6.8</version>
      </dependency>

   </dependencies>
</project>
package com.finddevguides;

public class Logging {

  /* *
   * This is the method which I would like to execute
 *before a selected method execution.
   */
   public void beforeAdvice() {
      System.out.println("Going to setup student profile.");
   }

  /* *
   * This is the method which I would like to execute
 *after a selected method execution.
   */
   public void afterAdvice() {
      System.out.println("Student profile has been setup.");
   }

  /* *
   * This is the method which I would like to execute
 *when any method returns.
   */
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }

  /**
 *This is the method which I would like to execute
   * if there is an exception raised.
    */
   public void AfterThrowingAdvice(IllegalArgumentException ex) {
      System.out.println("There has been an exception: " + ex.toString());
   }

}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();

      student.printThrowException();
   }
}

ステップ3 *- *src> main> resources フォルダーの下に構成ファイル Beans.xml を追加します。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id = "log" ref = "logging">
         <aop:PointCut id = "selectAll"
            expression = "execution(* com.finddevguides.*.*(..))"/>
         <aop:before PointCut-ref = "selectAll" method = "beforeAdvice"/>
         <aop:after PointCut-ref = "selectAll" method = "afterAdvice"/>
         <aop:after-returning PointCut-ref = "selectAll"
            returning = "retVal"
            method = "afterReturningAdvice"/>
         <aop:after-throwing PointCut-ref = "selectAll"
            throwing = "ex"
            method = "AfterThrowingAdvice"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

ステップ4 *-コマンドコンソールを開き、C:\ MVNディレクトリに移動して、次の *mvn コマンドを実行します。

C:\MVN>Student> mvn package

Mavenは必要なライブラリの処理とダウンロードを開始します。

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Student 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven
-jar-plugin/2.4/maven-jar-plugin-2.4.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-
jar-plugin/2.4/maven-jar-plugin-2.4.pom (6 KB at 2.2 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven
-jar-plugin/2.4/maven-jar-plugin-2.4.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-
jar-plugin/2.4/maven-jar-plugin-2.4.jar (34 KB at 31.6 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/springframework/spring-aop
/4.1.0.RELEASE/spring-aop-4.1.0.RELEASE.pom
Downloaded: https://repo.maven.apache.org/maven2/org/springframework/spring-aop/
4.1.0.RELEASE/spring-aop-4.1.0.RELEASE.pom (3 KB at 3.7 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/springframework/spring-bea
ns/4.1.0.RELEASE/spring-beans-4.1.0.RELEASE.pom
Downloaded: https://repo.maven.apache.org/maven2/org/springframework/spring-bean
s/4.1.0.RELEASE/spring-beans-4.1.0.RELEASE.pom (3 KB at 4.1 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/springframework/spring-cor
e/4.1.0.RELEASE/spring-core-4.1.0.RELEASE.pom
Downloaded: https://repo.maven.apache.org/maven2/org/springframework/spring-core
/4.1.0.RELEASE/spring-core-4.1.0.RELEASE.pom (3 KB at 4.0 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/springframework/spring-aop
/4.1.0.RELEASE/spring-aop-4.1.0.RELEASE.jar
Downloading: https://repo.maven.apache.org/maven2/org/springframework/spring-cor
e/4.1.0.RELEASE/spring-core-4.1.0.RELEASE.jar
Downloading: https://repo.maven.apache.org/maven2/org/springframework/spring-bea
ns/4.1.0.RELEASE/spring-beans-4.1.0.RELEASE.jar
Downloaded: https://repo.maven.apache.org/maven2/org/springframework/spring-aop/
4.1.0.RELEASE/spring-aop-4.1.0.RELEASE.jar (351 KB at 43.9 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/org/springframework/spring-bean
s/4.1.0.RELEASE/spring-beans-4.1.0.RELEASE.jar (685 KB at 37.5 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/org/springframework/spring-core
/4.1.0.RELEASE/spring-core-4.1.0.RELEASE.jar (982 KB at 47.1 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Student --
-
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\Student\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Student ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. b
uild is platform dependent!
[INFO] Compiling 1 source file to C:\MVN\Student\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ St
udent ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\Student\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ Student
 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. b
uild is platform dependent!
[INFO] Compiling 1 source file to C:\MVN\Student\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ Student ---
[INFO] Surefire report directory: C:\MVN\Student\target\surefire-reports
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/sure
fire-junit3/2.12.4/surefire-junit3-2.12.4.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/suref
ire-junit3/2.12.4/surefire-junit3-2.12.4.pom (2 KB at 1.3 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/sure
fire-junit3/2.12.4/surefire-junit3-2.12.4.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/suref
ire-junit3/2.12.4/surefire-junit3-2.12.4.jar (26 KB at 27.7 KB/sec)

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.finddevguides.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ Student ---
Downloading: https://repo.maven.apache.org/maven2/classworlds/classworlds/1.1-al
pha-2/classworlds-1.1-alpha-2.jar
Downloaded: https://repo.maven.apache.org/maven2/classworlds/classworlds/1.1-alp
ha-2/classworlds-1.1-alpha-2.jar (37 KB at 35.8 KB/sec)
[INFO] Building jar: C:\MVN\Student\target\Student-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 38.441 s
[INFO] Finished at: 2017-02-19T21:18:59+05:30
[INFO] Final Memory: 18M/109M
[INFO] ------------------------------------------------------------------------

Eclipseでプロジェクトをインポートする

  • ステップ1 *-Eclipseを開きます。
  • ステップ2 *-*ファイル→インポート→*オプションを選択します。
  • ステップ3 *-Mavenプロジェクトオプションを選択します。 [次へ]ボタンをクリックします。
  • ステップ4 *-学生プロジェクトがMavenを使用して作成されたプロジェクトの場所を選択します。
  • ステップ5 *-[完了]ボタンをクリックします。

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Name : Zara
Student profile has been setup.
Returning:Zara
Going to setup student profile.
Age : 11
Student profile has been setup.
Returning:11
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
Exception in thread "main" java.lang.IllegalArgumentException
   at com.finddevguides.Student.printThrowException(Student.java:25)

   at com.finddevguides.Student$$FastClassBySpringCGLIB$$7dc55815.invoke(<generated>)

   at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)

   at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)

   at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:43)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)

   at com.finddevguides.Student$$EnhancerBySpringCGLIB$$56a970f2.printThrowException(<generated>)

   at com.finddevguides.MainApp.main(MainApp.java:16)

Spring AOP-XMLベースのPointCut

参加ポイント

JoinPointは、AOPアスペクトをプラグインできるアプリケーション内のポイントを表します。 また、Spring AOPフレームワークを使用してアクションが実行されるアプリケーション内の実際の場所であるとも言えます。 次の例を考慮してください-

  • パッケージに含まれるすべてのメソッドクラス。
  • クラスの特定のメソッド。

ポイントカット

PointCutは、アドバイスを実行する必要がある1つ以上のJoinPointのセットです。 AOPの例で見るように、式またはパターンを使用してPointCutsを指定できます。 Springでは、PointCutは特定のJoinPointを使用してアドバイスを適用するのに役立ちます。 次の例を考慮してください-

  • 式= "execution(* com.finddevguides。(..))"
  • 式= "execution(* com.finddevguides.Student.getName(..))"

構文

<aop:config>
   <aop:aspect id = "log" ref = "adviceClass">
      <aop:PointCut id = "PointCut-id" expression = "execution( expression )"/>
   </aop:aspect>
</aop:config>

どこで、

  • adviceClass -アドバイスメソッドを含むクラスの参照
  • PointCut-id -PointCutのID
  • * execution(expression)*-アドバイスが適用されるメソッドをカバーする式。

JoinPointおよびPointCutに関連する上記の概念を理解するために、PointCutsのいくつかを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

public class Logging {

  /* *
   * This is the method which I would like to execute
 *before a selected method execution.
   */
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id = "log" ref = "logging">
         <aop:PointCut id = "selectAll"
         expression = "execution(* com.finddevguides.*.*(..))"/>
         <aop:before PointCut-ref = "selectAll" method = "beforeAdvice"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Name : Zara
Going to setup student profile.
Age : 11

上記で定義された<aop:pointcut>は、パッケージcom.finddevguidesで定義されたすべてのメソッドを選択します。 特定のメソッドの前後にアドバイスを実行したい場合、PointCutの定義の星印(*)を実際のクラス名とメソッド名に置き換えることにより、PointCutを定義して実行を絞り込むことができます。 以下は、概念を示すために変更されたXML構成ファイルです。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id = "log" ref = "logging">
         <aop:PointCut id = "selectAll"
            expression = "execution(* com.finddevguides.Student.getName(..))"/>
         <aop:before PointCut-ref = "selectAll" method = "beforeAdvice"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Name : Zara
Age : 11

Spring AOP-XMLベースのアドバイス

*Before* は、メソッドの実行前にアドバイスが実行されるようにするアドバイスタイプです。 以下は、事前アドバイスの構文です。

構文

<aop:config>
   <aop:aspect id = "log" ref = "logging">
      <aop:PointCut id = "PointCut-id" expression = "execution( expression )"/>
      <aop:before PointCut-ref = "PointCut-id" method = "methodName"/>
   </aop:aspect>
</aop:config>

どこで、

  • PointCut-id -PointCutのID。
  • methodName -呼び出された関数の前に呼び出される関数のメソッド名。

Before Adviceに関連する上記の概念を理解するために、Before Adviceを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

public class Logging {

  /* *
   * This is the method which I would like to execute
 *before a selected method execution.
   */
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id = "log" ref = "logging">
         <aop:PointCut id = "selectAll"
            expression = "execution(* com.finddevguides.Student.getName(..))"/>
         <aop:before PointCut-ref = "selectAll" method = "beforeAdvice"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Name : Zara
Age : 11

Spring AOP-XMLベースのアドバイス後

*After* は、メソッドの実行後にアドバイスが実行されるようにするアドバイスタイプです。 アフターアドバイスの構文は次のとおりです。

構文

<aop:config>
   <aop:aspect id = "log" ref = "logging">
      <aop:PointCut id = "PointCut-id" expression = "execution( expression )"/>
      <aop:after PointCut-ref = "PointCut-id" method = "methodName"/>
   </aop:aspect>
</aop:config>

どこで、

  • PointCut-id -PointCutのID。
  • methodName -呼び出された関数の後に呼び出される関数のメソッド名。

アフターアドバイスに関連する上記の概念を理解するために、アフターアドバイスを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

public class Logging {

  /* *
   * This is the method which I would like to execute
 *after a selected method execution.
   */
   public void afterAdvice(){
      System.out.println("Student profile setup complete.");
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id = "log" ref = "logging">
         <aop:PointCut id = "selectAll"
            expression = "execution(* com.finddevguides.Student.getAge(..))"/>
         <aop:after PointCut-ref = "selectAll" method = "afterAdvice"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションに問題がなければ、次のメッセージが出力されます。

Name : Zara
Age : 11
Student profile setup complete.

Spring AOP-アドバイスを返した後のXMLベース

*After* は、メソッドが正常に完了した場合にのみメソッド実行後にアドバイスが実行されるようにするアドバイスタイプです。 アフターアドバイスの構文は次のとおりです。

構文

<aop:config>
   <aop:aspect id = "log" ref = "logging">
      <aop:PointCut id = "PointCut-id" expression = "execution( expression )"/>
      <aop:after-returning PointCut-ref = "PointCut-id"
         returning = "retVal" method = "methodName"/>
   </aop:aspect>
</aop:config>

どこで、

  • PointCut-id -PointCutのID。
  • methodName -呼び出された関数が正常に戻った後に呼び出される関数のメソッド名。

After Returning Adviceに関連する上記の概念を理解するために、After Returning adviceを実装する例を記述しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

public class Logging {

  /* *
   * This is the method which I would like to execute
 *when any method returns.
   */
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id = "log" ref = "logging">
         <aop:PointCut id = "selectAll"
         expression = "execution(* com.finddevguides.*.*(..))"/>
         <aop:after-returning PointCut-ref = "selectAll"
            method = "afterReturningAdvice" returning = "retVal"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Name : Zara
Returning : Name
Age : 11
Exception raised

Spring AOP-投球アドバイス後のXMLベース

*After-throwing* は、メソッドが例外をスローして終了した場合にのみ、メソッドの実行後にアドバイスが実行されるようにするアドバイスタイプです。 以下は、投球後のアドバイスの構文です。

構文

<aop:config>
   <aop:aspect id = "log" ref = "logging">
      <aop:PointCut id = "PointCut-id" expression = "execution( expression )"/>
      <aop:after-throwing PointCut-ref = "PointCut-id" throwing = "ex"
         method = "methodName"/>
   </aop:aspect>
</aop:config>

どこで、

  • PointCut-id -PointCutのID。
  • ex -スローされる例外。
  • methodName -呼び出された関数が例外をスローして終了したときに呼び出される関数のメソッド名。

アフタースローアドバイスに関連する上記の概念を理解するために、アフタースローアドバイスを実装する例を記述しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

public class Logging {
  /**
 *This is the method which I would like to execute
   * if there is an exception raised.
    */
   public void afterThrowingAdvice(IllegalArgumentException ex) {
      System.out.println("There has been an exception: " + ex.toString());
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.printThrowException();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id = "log" ref = "logging">
         <aop:PointCut id = "selectAll"
         expression = "execution(* com.finddevguides.*.*(..))"/>
         <aop:after-throwing PointCut-ref = "selectAll"
            throwing = "ex" method = "afterThrowingAdvice"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Exception raised
There has been an exception: java.lang.IllegalArgumentException
Exception in thread "main" java.lang.IllegalArgumentException
   at com.finddevguides.Student.printThrowException(Student.java:25)

   at com.finddevguides.Student$$FastClassBySpringCGLIB$$7dc55815.invoke(<generated>>)

   at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)

   at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)

   at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)

   at com.finddevguides.Student$$EnhancerBySpringCGLIB$$8514cd8.printThrowException(<generated>)

   at com.finddevguides.MainApp.main(MainApp.java:15)

Spring AOP-XMLベースのアラウンドアドバイス

*Around* は、メソッドの実行の前後にアドバイスが実行されるようにするアドバイスタイプです。 以下はアラウンドアドバイスの構文です。

構文

<aop:config>
   <aop:aspect id = "log" ref = "logging">
      <aop:PointCut id = "PointCut-id" expression = "execution( expression )"/>
      <aop:around PointCut-ref = "PointCut-id" method = "methodName"/>
   </aop:aspect>
</aop:config>

どこで、

  • PointCut-id -PointCutのID。
  • methodName -呼び出された関数の前に呼び出される関数のメソッド名。

アラウンドアドバイスに関連する上記の概念を理解するために、アラウンドアドバイスを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;
import org.aspectj.lang.ProceedingJoinPoint;

public class Logging {

  /* *
   * This is the method which I would like to execute
 *around a selected method execution.
   */
   public String aroundAdvice(ProceedingJoinPoint jp) throws Throwable{
      System.out.println("Around advice");
      Object[] args = jp.getArgs();
      if(args.length>0){
         System.out.print("Arguments passed: " );
         for (int i = 0; i < args.length; i++) {
            System.out.print("arg "+(i+1)+": "+args[i]);
         }
      }

      Object result = jp.proceed(args);
      System.out.println("Returning " + result);
      return result.toString();
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id = "log" ref = "logging">
         <aop:PointCut id = "selectName"
            expression = "execution(* com.finddevguides.Student.getName(..))"/>
         <aop:around PointCut-ref = "selectName" method = "aroundAdvice"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Around advice
Name : Zara
Returning Zara

Spring AOP-注釈ベースのアプリケーション

注釈ベースの構成を使用してアドバイスを実装する例を作成しましょう。 このために、機能するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.PointCut;

@Aspect
public class Logging {

  /* *Following is the definition for a PointCut to select
   * all the methods available. So advice will be called
 *for all the methods.
   */
   @PointCut("execution(* com.finddevguides.*.*(..))")
   private void selectAll(){}

  /* *
   * This is the method which I would like to execute
 *before a selected method execution.
   */
   @Before("selectAll()")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Name : Zara
Going to setup student profile.
Age : 11

Spring AOP-注釈ベースのPointCut

JoinPoint

JoinPointは、AOPアスペクトをプラグインできるアプリケーション内のポイントを表します。 また、Spring AOPフレームワークを使用してアクションが実行されるアプリケーション内の実際の場所であるとも言えます。 次の例を考慮してください-

  • パッケージに含まれるすべてのメソッドクラス。
  • クラスの特定のメソッド。

ポイントカット

PointCutは、アドバイスを実行する1つ以上のJoinPointのセットです。 AOPの例で見るように、式またはパターンを使用してPointCutsを指定できます。 Springでは、PointCutは特定のJoinPointを使用してアドバイスを適用するのに役立ちます。 次の例を考慮してください-

  • @PointCut( "execution(* com.finddevguides。(..))")
  • @PointCut( "execution(* com.finddevguides.Student.getName(..))")

構文

@Aspect
public class Logging {

   @PointCut("execution(* com.finddevguides.*.*(..))")
   private void selectAll(){}

}

どこで、

  • @ Aspect -クラスをアドバイスメソッドを含むクラスとしてマークします。
  • @ PointCut -関数をPointCutとしてマークする
  • * execution(expression)*-アドバイスが適用されるメソッドをカバーする式。

JoinPointおよびPointCutに関連する上記の概念を理解するために、PointCutsのいくつかを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.PointCut;
import org.aspectj.lang.annotation.Before;

@Aspect
public class Logging {

  /* *Following is the definition for a PointCut to select
   * all the methods available. So advice will be called
 *for all the methods.
   */
   @PointCut("execution(* com.finddevguides.*.*(..))")
   private void selectAll(){}

  /* *
   * This is the method which I would like to execute
 *before a selected method execution.
   */
   @Before("selectAll()")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Name : Zara
Going to setup student profile.
Age : 11

上記で定義された@Pointcutは、式を使用して、パッケージcom.finddevguidesで定義されたすべてのメソッドを選択します。 @Beforeアドバイスでは、上記で定義したPointCutをパラメーターとして使用します。 上記のPointCutでカバーされるすべてのメソッドの前に、事実上beforeAdvice()メソッドが呼び出されます。

Spring AOP-アドバイスに基づく注釈

*@ Before* は、メソッドの実行前にアドバイスが実行されるようにするアドバイスタイプです。 @Beforeアドバイスの構文は次のとおりです。

構文

@PointCut("execution(* com.finddevguides.Student.getName(..))")
private void selectGetName(){}

@Before("selectGetName()")
public void beforeAdvice(){
   System.out.println("Going to setup student profile.");
}

どこで、

  • @ PointCut -関数をPointCutとしてマークする
  • * execution(expression)*-アドバイスが適用されるメソッドをカバーする式。
  • @ Before -PointCutでカバーされるメソッドの前に実行されるアドバイスとして関数をマークします。

@Before Adviceに関連する上記の概念を理解するために、@ Before Adviceを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.PointCut;
import org.aspectj.lang.annotation.Before;

@Aspect
public class Logging {

  /* *Following is the definition for a PointCut to select
   * all the methods available. So advice will be called
 *for all the methods.
   */
   @PointCut("execution(* com.finddevguides.Student.getName(..))")
   private void selectGetName(){}

  /* *
   * This is the method which I would like to execute
 *before a selected method execution.
   */
   @Before("selectGetName()")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Name : Zara
Age : 11

上記で定義された@Pointcutは、式を使用して、パッケージcom.finddevguidesのクラスで定義されたメソッドgetAge()を選択します。 @Afterアドバイスでは、上記で定義したPointCutをパラメーターとして使用します。 事実上、afterAdvice()メソッドは、上記のPointCutでカバーされるすべてのメソッドの前に呼び出されます。

Spring AOP-アドバイスに基づいた注釈ベース

*@ After* は、メソッドの実行後にアドバイスが実行されるようにするアドバイスタイプです。 @Afterアドバイスの構文は次のとおりです。

構文

@PointCut("execution(* com.finddevguides.Student.getAge(..))")
private void selectGetName(){}

@After("selectGetAge()")
public void afterAdvice(){
   System.out.println("Student profile setup completed.");
}

どこで、

  • @ PointCut -関数をPointCutとしてマークする
  • * execution(expression)*-アドバイスが適用されるメソッドをカバーする式。
  • @ After -PointCutでカバーされるメソッドの前に実行されるアドバイスとして関数をマークします。

@After Adviceに関連する上記の概念を理解するために、@ After Adviceを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.PointCut;
import org.aspectj.lang.annotation.After;

@Aspect
public class Logging {

  /* *Following is the definition for a PointCut to select
   * all the methods available. So advice will be called
 *for all the methods.
   */
   @PointCut("execution(* com.finddevguides.Student.getAge(..))")
   private void selectGetAge(){}

  /* *
   * This is the method which I would like to execute
 *after a selected method execution.
   */
   @After("selectGetAge()")
   public void afterAdvice(){
      System.out.println("Student profile setup completed.");
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Name : Zara
Age : 11
Student profile setup completed.

上記で定義された@Pointcutは、式を使用して、パッケージcom.finddevguidesのクラスで定義されたメソッドgetAge()を選択します。 @Afterアドバイスでは、上記で定義したPointCutをパラメーターとして使用します。 事実上、afterAdvice()メソッドは、上記のPointCutでカバーされるすべてのメソッドの前に呼び出されます。

Spring AOP-アドバイスを返した後の注釈ベース

*@ AfterReturning* はアドバイスタイプで、メソッドが正常に実行された後にアドバイスが実行されるようにします。 @AfterReturningアドバイスの構文は次のとおりです。

構文

@AfterReturning(PointCut = "execution(* com.finddevguides.Student.*(..))",
   returning = "retVal")
public void afterReturningAdvice(JoinPoint jp, Object retVal){
   System.out.println("Method Signature: "  + jp.getSignature());
   System.out.println("Returning:" + retVal.toString() );
}

どこで、

  • @ AfterReturning -メソッドが正常に戻った場合、PointCutでカバーされるメソッドの前に実行されるアドバイスとして関数をマークします。
  • PointCut -関数を選択する式を提供します
  • * execution(expression)*-アドバイスが適用されるメソッドをカバーする式。
  • returning -返される変数の名前。

@AfterReturning Adviceに関連する上記の概念を理解するために、@ AfterReturning Adviceを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;

@Aspect
public class Logging {

  /* *
   * This is the method which I would like to execute
 *after a selected method execution.
   */
   @AfterReturning(PointCut = "execution(* com.finddevguides.Student.*(..))",
      returning = "retVal")
   public void afterReturningAdvice(JoinPoint jp, Object retVal){
      System.out.println("Method Signature: "  + jp.getSignature());
      System.out.println("Returning:" + retVal.toString() );
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Age : 11
Method Signature: Integer com.finddevguides.Student.getAge()
Returning 11

Spring AOP-アドバイスを投げた後の注釈ベース

*@ AfterThrowing* は、メソッドが例外をスローした場合にアドバイスが実行されるようにするアドバイスタイプです。 @AfterThrowingアドバイスの構文は次のとおりです。

構文

@AfterThrowing(PointCut = "execution(* com.finddevguides.Student.*(..))",
   throwing = "error")
public void afterThrowingAdvice(JoinPoint jp, Throwable error){
   System.out.println("Method Signature: "  + jp.getSignature());
   System.out.println("Exception: "+error);
}

どこで、

  • @ AfterThrowing -メソッドが例外をスローする場合、PointCutでカバーされるメソッドの前に実行されるアドバイスとして関数をマークします。
  • PointCut -関数を選択する式を提供します。
  • * execution(expression)*-アドバイスが適用されるメソッドをカバーする式。
  • throwing -返される例外の名前。

@AfterThrowing Adviceに関連する上記の概念を理解するために、@ AfterThrowing Adviceを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;

@Aspect
public class Logging {

  /* *
   * This is the method which I would like to execute
 *after a selected method execution throws exception.
   */
   @AfterThrowing(PointCut = "execution(* com.finddevguides.Student.*(..))",
      throwing = "error")
   public void afterThrowingAdvice(JoinPoint jp, Throwable error){
      System.out.println("Method Signature: "  + jp.getSignature());
      System.out.println("Exception: "+error);
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.printThrowException();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Exception raised
Method Signature: void com.finddevguides.Student.printThrowException()
Exception: java.lang.IllegalArgumentException
Exception in thread "main" java.lang.IllegalArgumentException

   at com.finddevguides.Student.printThrowException(Student.java:25)

   at com.finddevguides.Student$$FastClassBySpringCGLIB$$7dc55815.invoke(<generated>)

   at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)

   at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)

   at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)

   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

   at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)

   at com.finddevguides.Student$$EnhancerBySpringCGLIB$$99b0a988.printThrowException(<generated>)

   at com.finddevguides.MainApp.main(MainApp.java:13)

Spring AOP-注釈ベースのアドバイス

*@ Around* はアドバイスタイプであり、メソッド実行の前後にアドバイスを実行できるようにします。 @Aroundアドバイスの構文は次のとおりです。

構文

@PointCut("execution(* com.finddevguides.Student.getAge(..))")
private void selectGetName(){}

@Around("selectGetAge()")
public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
   System.out.println("Around advice");
   Object[] args = jp.getArgs();
   if(args.length>0){
      System.out.print("Arguments passed: " );
      for (int i = 0; i < args.length; i++) {
         System.out.print("arg "+(i+1)+": "+args[i]);
      }
   }

   Object result = jp.proceed(args);
   System.out.println("Returning " + result);
   return result.toString();
}

どこで、

  • @ PointCut -関数をPointCutとしてマークする
  • * execution(expression)*-アドバイスが適用されるメソッドをカバーする式。
  • @ Around -PointCutでカバーされるメソッドの前に実行されるアドバイスとして関数をマークします。

@Around Adviceに関連する上記の概念を理解するために、@ Around Adviceを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.PointCut;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;

@Aspect
public class Logging {

  /* *Following is the definition for a PointCut to select
   * all the methods available. So advice will be called
 *for all the methods.
   */
   @PointCut("execution(* com.finddevguides.Student.getAge(..))")
   private void selectGetAge(){}

  /* *
   * This is the method which I would like to execute
 *around a selected method execution.
   */
   @Around("selectGetAge()")
   public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
      System.out.println("Around advice");
      Object[] args = proceedingJoinPoint.getArgs();
      if(args.length>0){
         System.out.print("Arguments passed: " );
         for (int i = 0; i < args.length; i++) {
            System.out.print("arg "+(i+1)+": "+args[i]);
         }
      }

      Object result = proceedingJoinPoint.proceed(args);
      System.out.println("Returning " + result);
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Around advice
Age : 11
Returning 11

Spring AOP-プロキシ

これまでのところ、 <aop:config> または <aop:aspectj-autoproxy> を使用してアスペクトを宣言しました。 プログラムでプロキシを作成したり、プロキシオブジェクトを使用してプログラムでアスペクトを呼び出したりできます。

構文

//Create object to be proxied
Student student = new Student();

//Create the Proxy Factory
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(student);

//Add Aspect class to the factory
proxyFactory.addAspect(Logging.class);

//Get the proxy object
Student proxyStudent = proxyFactory.getProxy();

//Invoke the proxied method.
proxyStudent.getAge();

どこで、

  • AspectJProxyFactory -プロキシオブジェクトを作成するファクトリクラス。
  • Logging.class -アドバイスを含むアスペクトのクラス。
  • 学生-アドバイスするビジネスクラス。

プロキシに関する上記の概念を理解するために、プロキシを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.PointCut;
import org.aspectj.lang.annotation.Before;

@Aspect
public class Logging {

  /* *Following is the definition for a PointCut to select
   * all the methods available. So advice will be called
 *for all the methods.
   */
   @PointCut("execution(* com.finddevguides.Student.getAge(..))")
   private void selectGetAge(){}

  /* *
   * This is the method which I would like to execute
 *before a selected method execution.
   */
   @Before("selectGetAge()")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.aop.aspectj.annotation.AspectJProxyFactory;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

     //Create the Proxy Factory
      AspectJProxyFactory proxyFactory = new AspectJProxyFactory(student);

     //Add Aspect class to the factory
      proxyFactory.addAspect(Logging.class);

     //Get the proxy object
      Student proxyStudent = proxyFactory.getProxy();

     //Invoke the proxied method.
      proxyStudent.getAge();

   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Age : 11

Spring AOP-カスタム注釈

PointCut式によると、アドバイスが意図されていない他のBeanに適用される場合があります。 たとえば、次の式を考えます。

execution(* com.finddevguides.*.getAge(..))

getAge()メソッドを使用して新しいSpring Beanが追加され、意図しない場合でもアドバイスが適用され始めます。 これを実現するために、カスタム注釈を作成し、アドバイスが適用されるメソッドに注釈を付けることができます。

@Before("@annotation(com.finddevguides.Loggable)")

@Before Adviceに関連する上記の概念を理解するために、@ Before Adviceを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を使用してSpringアプリケーションを作成します。

Step Description
1 Update the project Student created under chapter Spring AOP - Application.
2 Update the bean configuration and run the application as explained below.

以下は Logging.java ファイルの内容です。 これは実際にはアスペクトモジュールのサンプルであり、さまざまなポイントで呼び出されるメソッドを定義します。

package com.finddevguides;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class Logging {

  /* *
   * This is the method which I would like to execute
 *before a selected method execution.
   */
   @Before("@annotation(com.finddevguides.Loggable)")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
}

以下は Loggable.java ファイルの内容です-

package com.finddevguides;

public @interface Loggable {

}

以下は Student.java ファイルの内容です。

package com.finddevguides;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }

   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }

   @Loggable
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }

   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下は MainApp.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
   }
}

以下は、構成ファイル Beans.xml です。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id = "student" class = "com.finddevguides.Student">
      <property name = "name"  value = "Zara"/>
      <property name = "age"  value = "11"/>
   </bean>

   <!-- Definition for logging aspect -->
   <bean id = "logging" class = "com.finddevguides.Logging"/>

</beans>

プロジェクトを実行

ソースファイルと構成ファイルの作成が完了したら、アプリケーションを実行します。 アプリケーションでMainApp.javaを右クリックし、「Javaアプリケーションとして実行」コマンドを使用します。 アプリケーションで問題がなければ、次のメッセージが出力されます。

Going to setup student profile.
Name : Zara
Age : 11