- Spring 核心基礎
- Spring - 首頁
- Spring - 概述
- Spring - 架構
- Spring - 環境搭建
- Spring - Hello World 示例
- Spring - IoC 容器
- Spring - Bean 定義
- Spring - Bean 作用域
- Spring - Bean 生命週期
- Spring - Bean 後處理器
- Spring - Bean 定義繼承
- Spring - 依賴注入
- Spring - 注入內部 Bean
- Spring - 注入集合
- Spring - Bean 自動裝配
- 基於註解的配置
- Spring - 基於 Java 的配置
- Spring - Spring 中的事件處理
- Spring - Spring 中的自定義事件
- Spring - 使用 Spring 框架進行 AOP
- Spring - JDBC 框架
- Spring - 事務管理
- Spring - Web MVC 框架
- Spring - 使用 Log4J 進行日誌記錄
- Spring 問題與解答
- Spring - 問題與解答
- Spring 有用資源
- Spring - 快速指南
- Spring - 有用資源
- Spring - 討論
基於 AspectJ 的 Spring AOP
@AspectJ 指的是一種將方面宣告為使用 Java 5 註解進行註解的常規 Java 類的方法。透過在基於 XML Schema 的配置檔案中包含以下元素,可以啟用 @AspectJ 支援。
<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>
宣告切點
一個切點有助於確定要與不同通知一起執行的感興趣的連線點(即方法)。在使用基於 @AspectJ 的配置時,切點宣告包含兩個部分:
一個切點表示式,用於精確確定我們感興趣的方法執行。
一個切點簽名,包含一個名稱和任意數量的引數。方法的實際主體無關緊要,實際上應該為空。
以下示例定義了一個名為“businessService”的切點,該切點將匹配 com.xyz.myapp.service 包下類中每個方法的執行:
import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression
private void businessService() {} // signature
以下示例定義了一個名為“getname”的切點,該切點將匹配 com.tutorialspoint 包下 Student 類中 getName() 方法的執行:
import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.tutorialspoint.Student.getName(..))")
private void getname() {}
宣告通知
你可以使用 @{ADVICE-NAME} 註解宣告任何五種通知,如程式碼片段所示。這假設你已經定義了一個切點簽名方法 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 通知定義內聯切點的示例:
@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
...
}
基於 @AspectJ 的 AOP 示例
為了理解上述與基於 @AspectJ 的 AOP 相關的概念,讓我們編寫一個示例,該示例將實現一些通知。為了使用一些通知編寫我們的示例,讓我們準備一個可用的 Eclipse IDE,並採取以下步驟建立一個 Spring 應用程式:
| 步驟 | 描述 |
|---|---|
| 1 | 建立一個名為SpringExample的專案,並在建立的專案中的src資料夾下建立一個com.tutorialspoint包。 |
| 2 | 如Spring Hello World 示例章節中所述,使用新增外部 JAR選項新增所需的 Spring 庫。 |
| 3 | 在專案中新增 Spring AOP 特定的庫aspectjrt.jar、aspectjweaver.jar和aspectj.jar。 |
| 4 | 在com.tutorialspoint包下建立 Java 類Logging、Student和MainApp。 |
| 5 | 在src資料夾下建立 Bean 配置檔案Beans.xml。 |
| 6 | 最後一步是建立所有 Java 檔案和 Bean 配置檔案的內容,並按如下所述執行應用程式。 |
以下是Logging.java檔案的內容。這實際上是一個方面模組的示例,它定義了要在各個點呼叫的方法。
package com.tutorialspoint;
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.tutorialspoint.*.*(..))")
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.tutorialspoint;
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.tutorialspoint;
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.tutorialspoint.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>
<!-- Definition for logging aspect -->
<bean id = "logging" class = "com.tutorialspoint.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