Spring-aspectj-based-aop-appoach
@AspectJベースのSpringでのAOP
@AspectJは、アスペクトをJava 5アノテーションが付けられた通常のJavaクラスとして宣言するスタイルを指します。 @AspectJサポートは、XMLスキーマベースの構成ファイル内に次の要素を含めることで有効になります。
<aop:aspectj-autoproxy/>
また、アプリケーションのクラスパスに次のAspectJライブラリが必要です。 これらのライブラリは、AspectJインストールの「lib」ディレクトリにあります。それ以外の場合は、インターネットからダウンロードできます。
- aspectjrt.jar
- aspectjweaver.jar
- aspectj.jar
- aopalliance.jar
アスペクトを宣言する
アスペクトクラスは他の通常の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* は、さまざまなアドバイスで実行する対象の結合ポイント(つまりメソッド)を決定するのに役立ちます。 @AspectJベースの構成で作業中、ポイントカット宣言には2つの部分があります-
- 対象のメソッド実行を正確に決定するポイントカット式。
- 名前と任意の数のパラメーターで構成されるポイントカット署名。 メソッドの実際の本体は無関係であり、実際には空である必要があります。
次の例では、パッケージcom.xyz.myapp.serviceの下のクラスで利用可能なすべてのメソッドの実行に一致する 'businessService’という名前のポイントカットを定義しています-
import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.xyz.myapp.service.*.*(..))")//expression
private void businessService() {} //signature
次の例では、com.finddevguidesパッケージの下のStudentクラスで使用可能なgetName()メソッドの実行と一致する「getname」という名前のポイントカットを定義しています。
import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.finddevguides.Student.getName(..))")
private void getname() {}
アドバイスを宣言する
コードスニペットで指定されている@ \ {ADVICE-NAME}アノテーションを使用して、5つのアドバイスのいずれかを宣言できます。 これは、ポイントカット署名メソッド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(){
...
}
任意のアドバイスに対してポイントカットをインラインで定義できます。 以下は、アドバイスの前にインラインポイントカットを定義する例です-
@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
...
}
@AspectJベースのAOPの例
@AspectJベースのAOPに関連する上記の概念を理解するために、いくつかのアドバイスを実装する例を作成しましょう。 少しアドバイスをしてサンプルを作成するには、動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。
Steps | Description |
---|---|
1 | Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project. |
2 | Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. |
3 | Add Spring AOP specific libraries* aspectjrt.jar, aspectjweaver.jar and aspectj.jar *in the project. |
4 | Create Java classes* Logging*, Student and MainApp under the com.finddevguides package. |
5 | Create Beans configuration file Beans.xml under the src folder. |
6 | The final step is to create the content of all the Java files and Bean Configuration file 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;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
@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.");
}
/* *
* This is the method which I would like to execute
*after a selected method execution.
*/
@After("selectAll()")
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.
*/
@AfterReturning(pointcut = "selectAll()", returning = "retVal")
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 by any method.
*/
@AfterThrowing(pointcut = "selectAll()", throwing = "ex")
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();
}
}
以下は設定ファイル 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>
ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-
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
.....
other exception content