- Spring AOP 教程
- Spring AOP - 主页
- Spring AOP - 概述
- Spring AOP - 环境设置
- Spring AOP - 核心概念
- Spring AOP - 建议类型
- Spring AOP - 实现
- 通过XML配置示例
- Spring AOP - 应用
- Spring AOP - 切入点方法
- Spring AOP - 之前的建议
- Spring AOP - 后建议
- Spring AOP - 返回建议后
- Spring AOP - 抛出建议后
- Spring AOP - 围绕建议
- 通过注释示例
- Spring AOP - 应用
- Spring AOP - 切入点方法
- Spring AOP - 方面之前
- Spring AOP - 后建议
- Spring AOP - 返回建议后
- Spring AOP - 抛出建议后
- Spring AOP - 围绕建议
- Spring AOP 进阶
- Spring AOP - 代理
- Spring AOP - 自定义注解
- Spring AOP 有用资源
- Spring AOP - 快速指南
- Spring AOP - 有用的资源
- Spring AOP - 讨论
Spring AOP - 快速指南
Spring AOP - 概述
Spring框架的关键组件之一是面向方面编程(AOP)框架。面向方面的编程需要将程序逻辑分解为不同的部分,称为所谓的关注点。跨越应用程序多个点的功能称为横切关注点。这些横切关注点在概念上与应用程序的业务逻辑是分开的。日志记录、审计、声明性事务、安全性、缓存等方面有各种常见的好例子。
OOP 中模块化的关键单元是类,而 AOP 中模块化的单元是方面。依赖注入可以帮助您将应用程序对象彼此解耦,而 AOP 可以帮助您将横切关注点与其影响的对象解耦。AOP 就像 Perl、.NET、Java 等编程语言中的触发器。
Spring AOP 模块让拦截器拦截应用程序。例如,当执行方法时,您可以在方法执行之前或之后添加额外的功能。
Spring AOP - 环境设置
本章将指导您如何准备开发环境以开始使用 Spring 框架。它还将教您如何在设置 Spring 框架之前在您的计算机上设置 JDK、Maven 和 Eclipse -
第 1 步 - 设置 Java 开发工具包 (JDK)
您可以从 Oracle 的 Java 站点 - Java SE 下载下载最新版本的 SDK 。您将在下载的文件中找到安装 JDK 的说明,按照给定的说明进行安装和配置设置。最后设置 PATH 和 JAVA_HOME 环境变量以引用包含 java 和 javac 的目录,通常分别为 java_install_dir/bin 和 java_install_dir。
如果您运行的是 Windows 并已将 JDK 安装在 C:\jdk-11.0.11 中,则必须将以下行放入 C:\autoexec.bat 文件中。
set PATH=C:\jdk-11.0.11;%PATH% set JAVA_HOME=C:\jdk-11.0.11
或者,在 Windows NT/2000/XP 上,您必须右键单击“我的电脑”,选择“属性”→“高级”→“环境变量”。然后,您必须更新 PATH 值并单击“确定”按钮。
在 Unix(Solaris、Linux 等)上,如果 SDK 安装在 /usr/local/jdk-11.0.11 中并且您使用 C shell,则必须将以下内容放入 .cshrc 文件中。
setenv PATH /usr/local/jdk-11.0.11/bin:$PATH setenv JAVA_HOME /usr/local/jdk-11.0.11
或者,如果您使用集成开发环境 (IDE),如 Borland JBuilder、Eclipse、IntelliJ IDEA 或 Sun ONE Studio,则必须编译并运行一个简单的程序来确认 IDE 知道您安装了 Java 的位置。否则,您将必须按照 IDE 文档中的规定进行正确的设置。
第 2 步 - 设置 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
可以通过在 Unix(Solaris、Linux 等)机器上执行以下命令来启动 Eclipse -
$/usr/local/eclipse/eclipse
成功启动后,如果一切正常,那么它应该显示以下结果 -
第 3 步 - 下载 Maven 存档
从https://maven.apache.org/download.cgi下载 Maven 3.8.4 。
| 操作系统 | 档案名称 |
|---|---|
| Windows | apache-maven-3.8.4-bin.zip |
| Linux | Apache-maven-3.8.4-bin.tar.gz |
| 苹果 | Apache-maven-3.8.4-bin.tar.gz |
第 4 步 - 提取 Maven 存档
将存档解压到您想要安装 Maven 3.8.4 的目录。将从存档中创建子目录 apache-maven-3.8.4。
| 操作系统 | 位置(根据您的安装情况可能会有所不同) |
|---|---|
| Windows | C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 |
| Linux | /usr/local/apache-maven |
| 苹果 | /usr/local/apache-maven |
第 5 步 - 设置 Maven 环境变量
将 M2_HOME、M2、MAVEN_OPTS 添加到环境变量中。
| 操作系统 | 输出 |
|---|---|
| Windows | 使用系统属性设置环境变量。 M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 M2=%M2_HOME%\bin MAVEN_OPTS=-Xms256m -Xmx512m |
| Linux | 打开命令终端并设置环境变量。 导出 M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 导出 M2=$M2_HOME/bin 导出 MAVEN_OPTS=-Xms256m -Xmx512m |
| 苹果 | 打开命令终端并设置环境变量。 导出 M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 导出M2=$M2_HOME/bin 导出 MAVEN_OPTS=-Xms256m -Xmx512m |
步骤 6 - 将 Maven bin 目录位置添加到系统路径
现在将 M2 变量附加到系统路径。
| 操作系统 | 输出 |
|---|---|
| Windows | 将字符串 ;%M2% 附加到系统变量 Path 的末尾。 |
| Linux | 导出路径=$M2:$PATH |
| 苹果 | 导出路径=$M2:$PATH |
第 7 步 - 验证 Maven 安装
现在打开控制台并执行以下mvn命令。
| 操作系统 | 任务 | 命令 |
|---|---|---|
| Windows | 打开命令控制台 | c:\> mvn --版本 |
| Linux | 打开命令终端 | $ mvn --版本 |
| 苹果 | 打开终端 | 机器:~约瑟夫$ mvn --version |
最后,验证上述命令的输出,应如下所示 -
| 操作系统 | 输出 |
|---|---|
| Windows | Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Maven 主目录:C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 Java版本:11.0.11,供应商:Oracle Corporation,运行时:C:\Program Files\Java\jdk11.0.11\ 默认区域设置:en_IN,平台编码:Cp1252 操作系统名称:“windows 10”,版本:“10.0”,架构:“amd64”,系列:“windows” |
| Linux | Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java版本:11.0.11 Java 主目录:/usr/local/java-current/jre |
| 苹果 | Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java版本:11.0.11 Java 主目录:/Library/Java/Home/jre |
Spring AOP - 核心概念
在开始使用 AOP 之前,让我们先熟悉一下 AOP 概念和术语。这些术语并不是 Spring 特有的,而是与 AOP 相关。
| 先生。 | 条款和说明 |
|---|---|
| 1 | 方面 具有一组提供横切需求的 API 的模块。例如,日志记录模块将被称为用于日志记录的 AOP 方面。根据需求,应用程序可以具有任意数量的方面。 |
| 2 | 加入点 这代表您的应用程序中可以插入 AOP 方面的点。您也可以说,它是应用程序中使用 Spring AOP 框架执行操作的实际位置。 |
| 3 | 建议 这是方法执行之前或之后要采取的实际操作。这是 Spring AOP 框架在程序执行期间调用的实际代码段。 |
| 4 | 切入点 这是一组应在其中执行建议的一个或多个连接点。您可以使用表达式或模式指定切点,正如我们将在 AOP 示例中看到的那样。 |
| 5 | 介绍 简介允许您向现有类添加新方法或属性。 |
| 6 | 目标对象 被告知的对象由一个或多个方面组成。该对象将始终是代理对象。也称为建议对象。 |
| 7 | 编织 编织是将方面与其他应用程序类型或对象链接起来以创建建议对象的过程。这可以在编译时、加载时或运行时完成。 |
Spring AOP - 建议类型
Spring 方面可以使用下表中提到的五种建议。
| 先生。 | 建议和说明 |
|---|---|
| 1 | 前 在方法执行之前运行建议。 |
| 2 | 后 在方法执行后运行建议,无论其结果如何。 |
| 3 | 回国后 仅当方法成功完成时,才在方法执行后运行通知。 |
| 4 | 投掷后 仅当方法通过抛出异常退出时,才在方法执行后运行通知。 |
| 5 | 大约 在调用建议方法之前和之后运行建议。 |
Spring AOP - 实现
Spring支持@AspectJ注释风格方法和基于模式的方法来实现自定义方面。
基于XML模式
方面是使用常规类以及基于 XML 的配置来实现的。
要使用本节中描述的 AOP 命名空间标签,您需要导入 spring 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>
声明一个方面
使用<aop:aspect>元素声明切面,并使用ref属性引用支持 bean,如下所示。
<aop:config> <aop:aspect id = "myAspect" ref = "aBean"> ... </aop:aspect> </aop:config> <bean id = "aBean" class = "..."> ... </bean>
这里“aBean”将被配置并依赖注入,就像您在前面的章节中看到的任何其他 Spring bean 一样。
声明切入点
切入点有助于确定要使用不同建议执行的感兴趣的连接点(即方法)。在使用基于 XML 模式的配置时,切入点将定义如下 -
<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>
以下示例定义了一个名为“businessService”的切入点,它将与 com.tutorialspoint 包下的 Student 类中可用的 getName() 方法的执行相匹配。
<aop:config>
<aop:aspect id = "myAspect" ref = "aBean">
<aop:pointcut id = "businessService"
expression = "execution(* com.tutorialspoint.Student.getName(..))"/>
...
</aop:aspect>
</aop:config>
<bean id = "aBean" class = "...">
...
</bean>
申报建议
您可以使用 <aop:{ADVICE NAME}> 元素在 <aop:aspect> 内声明五个建议中的任何一个,如下所示。
<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 类的样式。通过在基于 XML 模式的配置文件中包含以下元素来启用 @AspectJ 支持。
<aop:aspectj-autoproxy/>
声明一个方面
Aspects 类与任何其他普通 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(){
...
}
Spring AOP - 基于 XML 的应用程序
在本章中,我们将使用 Spring AOP 框架编写实际的 AOP 应用程序。在开始使用 Spring-WS 框架编写第一个示例之前,您必须确保已按照Spring Web 服务 - 环境设置一章中的说明正确设置 Spring AOP 环境。
现在,继续编写一个简单的基于控制台的 Spring AOP 应用程序,它将演示 AOP 概念。
创建一个项目
步骤 1 - 打开命令控制台,进入 C:\MVN 目录并执行以下mvn命令。
C:\MVN>mvn archetype:generate -DgroupId=com.tutorialspoint -DartifactId=Student -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Maven 将开始处理并创建完整的 Java 应用程序项目结构。
[INFO] Scanning for projects... [INFO] [INFO] ------------------< org.apache.maven:standalone-pom >------------------- [INFO] Building Maven Stub Project (No POM) 1 [INFO] --------------------------------[ pom ]--------------------------------- [INFO] [INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] [INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Batch mode [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: basedir, Value: C:\MVN [INFO] Parameter: package, Value: com.tutorialspoint [INFO] Parameter: groupId, Value: com.tutorialspoint [INFO] Parameter: artifactId, Value: Student [INFO] Parameter: packageName, Value: com.tutorialspoint [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: 13.388 s [INFO] Finished at: 2021-12-27T20:18:26+05:30 [INFO] ------------------------------------------------------------------------
步骤 2 - 转到 C:/MVN 目录。您将看到一个已创建的 Java 应用程序项目,名为 Student(如artifactId 中所指定)。更新 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.tutorialspoint</groupId>
<artifactId>Student</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Student</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.14</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
</dependencies>
</project>
以下是Logging.java文件的内容。
package com.tutorialspoint;
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.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();
}
}
步骤 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.tutorialspoint.*.*(..))"/>
<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.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>
步骤 4 - 打开命令控制台,进入 C:\MVN 目录并执行以下mvn命令。
C:\MVN>Student> mvn package
Maven 将开始处理并下载所需的库。
C:\MVN\Student>mvn package [INFO] Scanning for projects... [INFO] [INFO] ---------------------< com.tutorialspoint:Student >--------------------- [INFO] Building Student 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Student --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 1 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Student --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ Student --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory C:\MVN\Student\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ Student --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ Student --- [INFO] Surefire report directory: C:\MVN\Student\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.tutorialspoint.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.093 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ Student --- [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.213 s [INFO] Finished at: 2021-12-27T20:42:00+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN\Student>
在 Eclipse 中导入项目
步骤 1 - 打开 Eclipse。
步骤 2 - 选择文件 → 导入 →选项。
步骤 3 - 选择 Maven 项目选项。单击下一步按钮。
步骤 4 - 选择项目位置,其中学生项目是使用 Maven 创建的。
步骤 5 - 单击“完成”按钮。
运行项目
创建完源文件和配置文件后,运行您的应用程序。右键单击应用程序中的 MainApp.java 并使用run as Java Application命令。如果您的应用程序一切正常,它将打印以下消息。
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.tutorialspoint.Student.printThrowException(Student.java:25) ...
Spring AOP - 基于 XML 的切入点
加入点
JoinPoint 代表应用程序中可以插入 AOP 方面的点。您也可以说,它是应用程序中使用 Spring AOP 框架执行操作的实际位置。考虑以下示例 -
包中包含的所有方法类。
类的特定方法。
切入点
PointCut 是一组一个或多个应在其中执行建议的连接点。您可以使用表达式或模式指定切点,正如我们将在 AOP 示例中看到的那样。在 Spring 中,PointCut 有助于使用特定的 JoinPoints 来应用建议。考虑以下示例 -
表达式 =“执行(* com.tutorialspoint.*.*(..))”
表达式 = "执行(* com.tutorialspoint.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 - 切点的 id
execution( expression ) - 涵盖要应用建议的方法的表达式。
为了理解上述与 JoinPoint 和 PointCut 相关的概念,让我们编写一个示例来实现一些 PointCut。为了编写我们的示例并提供一些建议,让我们有一个可用的 Eclipse IDE,并使用以下步骤创建一个 Spring 应用程序。
| 步 | 描述 |
|---|---|
| 1 | 更新在Spring AOP - 应用程序一章下创建的项目Student。 |
| 2 | 更新 bean 配置并运行应用程序,如下所述。 |
以下是Logging.java文件的内容。这实际上是方面模块的示例,它定义了在各个点调用的方法。
package com.tutorialspoint;
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.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();
}
}
以下是配置文件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.tutorialspoint.*.*(..))"/>
<aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>
</aop:aspect>
</aop:config>
<!-- 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 Going to setup student profile. Age : 11
上面定义的<aop:pointcut>选择了com.tutorialspoint包下定义的所有方法。让我们假设,您想要在特定方法之前或之后执行您的建议,您可以通过用实际的类和方法名称替换 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.tutorialspoint.Student.getName(..))"/>
<aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>
</aop:aspect>
</aop:config>
<!-- 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>
运行项目
创建完源文件和配置文件后,运行您的应用程序。右键单击应用程序中的 MainApp.java 并使用run as Java Application命令。如果您的应用程序一切正常,它将打印以下消息。
Going to setup student profile. Name : Zara Age : 11
Spring AOP - 基于 XML 的前置建议
Before是一种建议类型,可确保建议在方法执行之前运行。以下是 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 - 切点的 id。
methodName - 在被调用函数之前调用的函数的方法名称。
为了理解上述与 Before Advice 相关的概念,让我们编写一个示例,该示例将实现 Before Advice。为了编写我们的示例并提供一些建议,让我们有一个可用的 Eclipse IDE,并使用以下步骤创建一个 Spring 应用程序。
| 步 | 描述 |
|---|---|
| 1 | 更新在Spring AOP - 应用程序一章下创建的项目Student。 |
| 2 | 更新 bean 配置并运行应用程序,如下所述。 |
以下是Logging.java文件的内容。这实际上是方面模块的示例,它定义了在各个点调用的方法。
package com.tutorialspoint;
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.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();
}
}
以下是配置文件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.tutorialspoint.Student.getName(..))"/>
<aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>
</aop:aspect>
</aop:config>
<!-- 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>
运行项目
创建完源文件和配置文件后,运行您的应用程序。右键单击应用程序中的 MainApp.java 并使用run as Java Application命令。如果您的应用程序一切正常,它将打印以下消息。
Going to setup student profile. Name : Zara Age : 11
Spring AOP - 基于 XML 的后续建议
After是一种建议类型,可确保建议在方法执行后运行。以下是 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 - 切点的 id。
methodName - 在被调用函数之后调用的函数的方法名称。
为了理解上述与 After Advice 相关的概念,让我们编写一个实现 After Advice 的示例。为了编写我们的示例并提供一些建议,让我们有一个可用的 Eclipse IDE,并使用以下步骤创建一个 Spring 应用程序。
| 步 | 描述 |
|---|---|
| 1 | 更新在Spring AOP - 应用程序一章下创建的项目Student。 |
| 2 | 更新 bean 配置并运行应用程序,如下所述。 |
以下是Logging.java文件的内容。这实际上是方面模块的示例,它定义了在各个点调用的方法。
package com.tutorialspoint;
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.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();
}
}
以下是配置文件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.tutorialspoint.Student.getAge(..))"/>
<aop:after pointcut-ref = "selectAll" method = "afterAdvice"/>
</aop:aspect>
</aop:config>
<!-- 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>
运行项目
创建完源文件和配置文件后,运行您的应用程序。右键单击应用程序中的 MainApp.java 并使用run as Java Application命令。如果您的应用程序一切正常,这将打印以下消息。
Name : Zara Age : 11 Student profile setup complete.
Spring AOP - 基于 XML 返回建议后
After是一种通知类型,确保仅当方法成功完成时通知才会在方法执行后运行。以下是 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 - 切点的 id。
methodName - 被调用函数成功返回后要调用的函数的方法名称。
为了理解上述与 After Returning Advice 相关的概念,让我们编写一个示例来实现 After Returning Advice。为了编写我们的示例并提供一些建议,让我们有一个可用的 Eclipse IDE,并使用以下步骤创建一个 Spring 应用程序 -
| 步 | 描述 |
|---|---|
| 1 | 更新在Spring AOP - 应用程序一章下创建的项目Student。 |
| 2 | 更新 bean 配置并运行应用程序,如下所述。 |
以下是Logging.java文件的内容。这实际上是方面模块的示例,它定义了在各个点调用的方法。
package com.tutorialspoint;
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.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 );
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.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();
}
}
以下是配置文件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.tutorialspoint.*.*(..))"/>
<aop:after-returning pointcut-ref = "selectAll"
method = "afterReturningAdvice" returning = "retVal"/>
</aop:aspect>
</aop:config>
<!-- 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>
运行项目
创建完源文件和配置文件后,运行您的应用程序。右键单击应用程序中的 MainApp.java 并使用run as Java Application命令。如果您的应用程序一切正常,它将打印以下消息。
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 - 切点的 id。
ex - 要抛出的异常。
methodName - 当被调用函数抛出异常并退出时要调用的函数的方法名称。
为了理解上述与 After Throwing Advice 相关的概念,让我们编写一个示例来实现 After Throwing Advice。为了编写我们的示例并提供一些建议,让我们有一个可用的 Eclipse IDE,并使用以下步骤创建一个 Spring 应用程序 -
| 步 | 描述 |
|---|---|
| 1 | 更新在Spring AOP - 应用程序一章下创建的项目Student。 |
| 2 | 更新 bean 配置并运行应用程序,如下所述。 |
以下是Logging.java文件的内容。这实际上是方面模块的示例,它定义了在各个点调用的方法。
package com.tutorialspoint;
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.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.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.tutorialspoint.*.*(..))"/>
<aop:after-throwing pointcut-ref = "selectAll"
throwing = "ex" method = "afterThrowingAdvice"/>
</aop:aspect>
</aop:config>
<!-- 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>
运行项目
创建完源文件和配置文件后,运行您的应用程序。右键单击应用程序中的 MainApp.java 并使用run as Java Application命令。如果您的应用程序一切正常,它将打印以下消息。
Exception raised There has been an exception: java.lang.IllegalArgumentException Exception in thread "main" java.lang.IllegalArgumentException at com.tutorialspoint.Student.printThrowException(Student.java:25) ...
Spring AOP - 基于 XML 的建议
around是一种建议类型,可确保建议在方法执行之前和之后运行。以下是 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 - 切点的 id。
methodName - 在被调用函数之前调用的函数的方法名称。
为了理解上述与周围建议相关的概念,让我们编写一个实现周围建议的示例。为了编写我们的示例并提供一些建议,让我们有一个可用的 Eclipse IDE,并使用以下步骤创建一个 Spring 应用程序 -
| 步 | 描述 |
|---|---|
| 1 | 更新在Spring AOP - 应用程序一章下创建的项目Student。 |
| 2 | 更新 bean 配置并运行应用程序,如下所述。 |
以下是Logging.java文件的内容。这实际上是方面模块的示例,它定义了在各个点调用的方法。
package com.tutorialspoint;
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.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("Ex