Springaop 简明教程
Spring AOP - Overview
Spring 框架一个主要组件是 Aspect Oriented Programming (AOP) 框架。面向方面的编程将程序逻辑分解成称为 so-called concerns 的不同部分。跨越应用程序多个点的功能被称为横切关注点。这些 cross-cutting concerns 在概念上独立于应用程序的业务逻辑。有许多方面的典型示例,如日志记录、审计、声明式事务、安全性、缓存等。
One of the key components of Spring Framework is the Aspect Oriented Programming (AOP) framework. Aspect Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns. These cross-cutting concerns are conceptually separate from the application’s business logic. There are various common good examples of aspects such as logging, auditing, declarative transactions, security, caching, etc.
OOP 中模块性的一个主要单元是类,而 AOP 中的模块性单元是方面。依赖关系注入可帮助你解耦应用程序对象,而 AOP 可帮助你解耦横切关注点与它们影响的对象。AOP 类似于 Perl、.NET、Java 和其他编程语言中的触发器。
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other, while AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others.
Spring AOP 模块让拦截器拦截应用程序。例如,当执行一个方法时,你可以在方法执行之前或之后添加额外的功能。
Spring AOP module lets interceptors intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution.
Spring AOP - Environment Setup
本章将在您开始使用 Spring 框架时,指导您如何准备开发环境。它还将教您在设置 Spring 框架之前如何在您的机器上设置 JDK、Maven 和 Eclipse −
This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework −
Step 1 - Setup Java Development Kit (JDK)
你可以从 Oracle 的 Java 站点下载 SDK 的最新版本 − Java SE Downloads. 你在下载文件中可以找到安装 JDK 的说明,按照给定的说明进行安装和配置。最后设置 PATH 和 JAVA_HOME 环境变量以引用包含 java 和 javac 的目录,通常分别为 java_install_dir/bin 和 java_install_dir。
You can download the latest version of SDK from Oracle’s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
如果您运行的是 Windows 且在 C:\jdk-11.0.11 中安装了 JDK,那么您将不得不把以下代码行放入您的 C:\autoexec.bat 文件中。
If you are running Windows and have installed the JDK in C:\jdk-11.0.11, you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk-11.0.11;%PATH%
set JAVA_HOME=C:\jdk-11.0.11
或者,在 Windows NT/2000/XP 中,你必须右键单击我的电脑,选择属性 → 高级 → 环境变量。然后,你将不得不更新 PATH 值并单击确定按钮。
Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.
在 Unix(Solaris、Linux 等)中,如果 SDK 安装在 /usr/local/jdk-11.0.11 且您使用 C shell,那么您将不得不把以下代码行放入您的 .cshrc 文件中。
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file.
setenv PATH /usr/local/jdk-11.0.11/bin:$PATH
setenv JAVA_HOME /usr/local/jdk-11.0.11
或者,如果你使用诸如 Borland JBuilder、Eclipse、IntelliJ IDEA 或 Sun ONE Studio 这样的集成开发环境 (IDE),则必须编译并运行一个简单程序来确认 IDE 知道你在何处安装了 Java。否则,你必须按照 IDE 文档中给出的内容执行正确的设置。
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.
Step 2 - Setup Eclipse IDE
本教程中的所有示例都是使用 Eclipse IDE 编写的。因此,我们建议你应该在你机器上安装 Eclipse 的最新版本。
All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine.
要安装 Eclipse IDE,请从 https://www.eclipse.org/downloads/ 下载最新的 Eclipse 二进制文件。下载安装后,将二进制发行版解压缩到方便的位置。例如,在 Windows 上的 C:\eclipse,或在 Linux/Unix 上的 /usr/local/eclipse,最后适当设置 PATH 变量。
To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.
可以通过在 Windows 机器上执行以下命令启动 Eclipse,或者你只需双击 eclipse.exe
Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe
%C:\eclipse\eclipse.exe
可以通过在 Unix(Solaris、Linux 等)机器上执行以下命令启动 Eclipse −
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$/usr/local/eclipse/eclipse
成功启动后,如果一切正常,它应该显示以下结果 −
After a successful startup, if everything is fine then it should display the following result −

Step 3 - Download Maven Archive
从 https://maven.apache.org/download.cgi 下载 Maven 3.8.4。
Download Maven 3.8.4 from https://maven.apache.org/download.cgi.
OS |
Archive name |
Windows |
apache-maven-3.8.4-bin.zip |
Linux |
apache-maven-3.8.4-bin.tar.gz |
Mac |
apache-maven-3.8.4-bin.tar.gz |
Step 4 - Extract the Maven Archive
将存档解压到要安装 Maven 3.8.4 的目录。存档将创建一个子目录 apache-maven-3.8.4。
Extract the archive, to the directory you wish to install Maven 3.8.4. The subdirectory apache-maven-3.8.4 will be created from the archive.
OS |
Location (can be different based on your installation) |
Windows |
C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 |
Linux |
/usr/local/apache-maven |
Mac |
/usr/local/apache-maven |
Step 5 - Set Maven Environment Variables
将 M2_HOME、M2、MAVEN_OPTS 添加到环境变量。
Add M2_HOME, M2, MAVEN_OPTS to environment variables.
OS |
Output |
Windows |
Set the environment variables using system properties. M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 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.8.4 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.8.4 export M2=$M2_HOME/bin export MAVEN_OPTS=-Xms256m -Xmx512m |
Step 6 - Add Maven bin Directory Location to System Path
现在将 M2 变量附加到系统路径。
Now append M2 variable to System Path.
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 |
Step 7 - Verify Maven Installation
现在打开控制台并执行以下 mvn 命令。
Now open console and execute the following mvn command.
OS |
Task |
Command |
Windows |
Open Command Console |
c:> mvn --version |
Linux |
Open Command Terminal |
$ mvn --version |
Mac |
Open Terminal |
machine:~ joseph$ mvn --version |
最后,验证上述命令的输出,其应如下所示 −
Finally, verify the output of the above commands, which should be as follows −
OS |
Output |
Windows |
Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Maven home: C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 Java version: 11.0.11, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk11.0.11\ Default locale: en_IN, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" |
Linux |
Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java version: 11.0.11 Java home: /usr/local/java-current/jre |
Mac |
Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java version: 11.0.11 Java home: /Library/Java/Home/jre |
Spring AOP - Core Concepts
在我们开始使用 AOP 之前,让我们先熟悉 AOP 概念和术语。这些术语不仅仅针对 Spring,而是与 AOP 相关。
Before we start working with AOP, let us become familiar with the AOP concepts and terminologies. These terms are not specific to Spring, rather they are related to AOP.
Sr.No. |
Terms & Description |
1 |
Aspect A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. |
2 |
Join point This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. |
3 |
Advice This is the actual action to be taken either before or after the method execution. This is the actual piece of code that is invoked during program execution by Spring AOP framework. |
4 |
PointCut This is a set of one or more joinpoints where an advice should be executed. You can specify PointCuts using expressions or patterns as we will see in our AOP examples. |
5 |
Introduction An introduction allows you to add new methods or attributes to existing classes. |
6 |
Target object The object being advised by one or more aspects. This object will always be a proxied object. Also referred to as the advised object. |
7 |
Weaving Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime. |
Spring AOP - Advice Types
Spring 方面可用于以下表格中提到的五种建议。
Spring aspects can work with five kinds of advice mentioned in the following table.
Sr.No. |
Advice & Description |
1 |
before Run advice before the method execution. |
2 |
after Run advice after the method execution, regardless of its outcome. |
3 |
after-returning Run advice after the method execution, only if the method completes successfully. |
4 |
after-throwing Run advice after the method execution, only if the method exits by throwing an exception. |
5 |
around Run advice before and after the advised method is invoked. |
Spring AOP - Implementations
Spring 支持 @AspectJ annotation style 方法和 schema-based 方法来实现自定义方面。
Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects.
XML Schema Based
方面使用常规类和基于 XML 的配置进行实现。
Aspects are implemented using regular classes along with XML based configuration.
若要使用本节中所述的 AOP 命名空间标签,你需要导入 Spring AOP 架构,如下所示
To use the AOP namespace tags described in this section, you need to import the spring AOP schema, described as follows −
<?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>
Declaring an Aspect
aspect 使用 <aop:aspect> 元素声明,且背景 Bean 使用 ref 特性引用,如下所示。
An aspect is declared using the <aop:aspect> element, and the backing bean is referenced using the ref attribute as follows.
<aop:config>
<aop:aspect id = "myAspect" ref = "aBean">
...
</aop:aspect>
</aop:config>
<bean id = "aBean" class = "...">
...
</bean>
这里,“aBean”将被配置且依赖注入,正如你在前几章所看到的那样。
Here "aBean" will be configured and dependency injected just like any other Spring bean as you have seen in the previous chapters.
Declaring a Pointcut
Pointcut 有助于确定要使用不同的建议执行的目标连接点(即方法)。在基于 XML 架构的配置中工作时,Pointcut 将被定义如下
A Pointcut helps in determining the join points (i.e. methods) of interest to be executed with different advices. While working with XML Schema based configuration, Pointcut will be defined as follows −
<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”的 Pointcut,它将匹配 Student 类中可用 getName() 方法在 com.tutorialspoint 包中的执行。
The following example defines a Pointcut named 'businessService' that will match the execution of getName() method available in Student class under the package com.tutorialspoint.
<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>
Declaring Advices
你可以使用 <aop:{ADVICE NAME}> 元素在 <aop:aspect> 内声明任意五个建议,如下所示。
You can declare any of the five advices inside an <aop:aspect> using the <aop:{ADVICE NAME}> element as follows.
<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 或不同的方法。这些方法将被定义为方面模块的一部分。
You can use same doRequiredTask or different methods for different advices. These methods will be defined as a part of aspect module.
@AspectJ based
@AspectJ 指一种将方面声明为使用 Java 5 注释注释的常规 Java 类的样式。通过在基于 XML 架构的配置文件中加入以下元素,可启用 @AspectJ 支持。
@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. The @AspectJ support is enabled by including the following element inside your XML Schema-based configuration file.
<aop:aspectj-autoproxy/>
Declaring an Aspect
方面类与任何其他常规 Bean 一样,可能有方法和字段,就像任何其他类一样,只不过它们将使用 @Aspect 注释,如下所示。
Aspects classes are like any other normal bean and may have methods and fields just like any other class, except that they will be annotated with @Aspect as follows.
package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AspectModule {
}
它们将在 XML 中配置,就像其他 Bean 一样,如下所示。
They will be configured in XML like any other bean as follows.
<bean id = "myAspect" class = "org.xyz.AspectModule">
<!-- configure properties of aspect here as normal -->
</bean>
Declaring a Pointcut
Pointcut 有助于确定要使用不同的建议执行的目标连接点(即方法)。在基于 @AspectJ 的配置中工作时,Pointcut 声明有以下两个部分
A Pointcut helps in determining the join points (i.e. methods) of interest to be executed with different advices. While working with @AspectJ based configuration, Pointcut declaration has two parts −
-
A Pointcut expression that determines exactly which method executions we are interested in.
-
A Pointcut signature comprising a name and any number of parameters. The actual body of the method is irrelevant and in fact should be empty.
以下示例定义了一个名为“businessService”的切点,它将匹配包 com.xyz.myapp.service 下的类中所有可用方法的执行。
The following example defines a Pointcut named 'businessService' that will match the execution of every method available in the classes under the package 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() 方法的执行。
The following example defines a Pointcut named 'getname' that will match the execution of getName() method available in Student class under the package com.tutorialspoint.
import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.tutorialspoint.Student.getName(..))")
private void getname() {}
Declaring Advices
您可以使用 @{ADVICE-NAME} 注解声明以下任何五种建议。这假定您已定义了切点签名方法 businessService()。
You can declare any of the five advices using @{ADVICE-NAME} annotations as given below. This assumes that you already have defined a Pointcut signature method 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(){
...
}
您可以为任何建议内联定义切点。下面是为前置建议定义内联切点的示例。
You can define Pointcut inline for any of the advices. Following is an example to define inline Pointcut for before advice.
@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
...
}
Spring AOP - XML Based Application
在本章中,我们将使用 Spring AOP 框架编写实际的 AOP 应用程序。在开始使用 Spring-WS 框架编写第一个示例之前,您必须确保已按照 Spring Web Services - Environment Setup 章节中的说明正确设置 Spring AOP 环境。
In this chapter, we will write actual AOP applications using Spring AOP Framework. Before you start writing your first example using Spring-WS framework, you have to make sure that you have set up your Spring AOP environment properly as explained in Spring Web Services - Environment Setup chapter.
现在,继续编写一个简单的基于控制台的 Spring AOP 应用程序,该应用程序将演示 AOP 概念。
Now, proceed to write a simple console-ased Spring AOP Application, which will demonstrate AOP concepts.
Create a Project
Step 1 − 打开命令控制台,转到 C:\MVN 目录并执行以下 mvn 命令。
Step 1 − Open a command console, go the C:\MVN directory and execute the following mvn command.
C:\MVN>mvn archetype:generate -DgroupId=com.tutorialspoint
-DartifactId=Student -DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
Maven 将开始处理并将创建完整的 Java 应用程序项目结构。
Maven will start processing and will create the complete Java application project structure.
[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] ------------------------------------------------------------------------
Step 2 − 转到 C:/MVN 目录。您将看到一个 Java 应用程序项目已创建,名为 student(如 artifactId 中指定)。更新 POM.xml 以包括 Spring-AOP 依赖项。添加 MainApp.java、Student.java 和 Logging.java 文件。
Step 2 − Go to C:/MVN directory. You’ll see a Java application project created, named student (as specified in artifactId). Update the POM.xml to include Spring-AOP dependencies. Add MainApp.java, Student.java, and Logging.java files.
POM.xml
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 文件的内容。
Following is the content of the Logging.java file.
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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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();
}
}
Step 3 − 在 src > main > resources 文件夹下添加 Beans.xml 配置文件。
Step 3 − Add the configuration file Beans.xml under src > main > resources folder.
<?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>
Step 4 − 打开命令控制台,转到 C:\MVN 目录并执行以下 mvn 命令。
Step 4 − Open the command console, go the C:\MVN directory and execute the following mvn command.
C:\MVN>Student> mvn package
Maven 将开始处理和下载所需的库。
Maven will start processing and downloading the required libraries.
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>
Import Project in Eclipse
Step 1 − 打开 Eclipse。
Step 1 − Open Eclipse.
Step 2 − 选择 File → Import → 选项。
Step 2 − Select File → Import → option.
Step 3 − 选择 Maven 项目选项。单击“下一步”按钮。
Step 3 − Select Maven Projects Option. Click the Next Button.
Step 4 − 选择项目位置,即使用 Maven 创建 Student 项目的位置。
Step 4 − Select Project location, where Student project was created using Maven.
Step 5 − 单击“完成”按钮。
Step 5 − Click Finish Button.
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
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 Based PointCut
Join Point
结合点表示您可以插入 AOP 方面的应用程序中的一个点。您还可以说,这是使用 Spring AOP 框架将在应用程序中执行操作的实际位置。考虑以下示例 −
A JoinPoint represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. Consider the following examples −
-
All methods classes contained in a package(s).
-
A particular methods of a class.
PointCut
切点是一组或更多连接点,某些建议应该在其中执行。你可以使用表达式或模式来指定切点,就像我们在 AOP 示例中看到的。在 Spring 中,切点能够帮助使用特定的连接点来应用建议。考虑以下示例:
PointCut is a set of one or more JoinPoints where an advice should be executed. You can specify PointCuts using expressions or patterns as we will see in our AOP examples. In Spring, PointCut helps to use specific JoinPoints to apply the advice. Consider the following examples −
-
expression = "execution(* com.tutorialspoint..(..))"
-
expression = "execution(* com.tutorialspoint.Student.getName(..))"
Syntax
<aop:config>
<aop:aspect id = "log" ref = "adviceClass">
<aop:pointcut id = "PointCut-id" expression = "execution( expression )"/>
</aop:aspect>
</aop:config>
其中,
Where,
-
adviceClass − ref of the class containing advice methods
-
PointCut-id − id of the PointCut
-
execution( expression ) − Expression covering methods on which advice is to be applied.
为了理解与连接点和切点相关的上述概念,让我们写一个示例,该示例将实现一些切点。为了编写我们带有少许建议的示例,让我们使用现成的 Eclipse IDE,并使用以下步骤来创建 Spring 应用程序。
To understand the above-mentioned concepts related to JoinPoint and PointCut, let us write an example which will implement few of the PointCuts. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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 配置文件,就运行该应用程序。如果你的应用程序一切正常,它将打印以下信息。
Once you are done with creating the source and bean configuration files, run the application. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Going to setup student profile.
Age : 11
上面定义的 <aop:pointcut> 选择在包 com.tutorialspoint 下定义的所有方法。假设你想在某个特定方法之前或之后执行你的建议,你可以定义你的切点,以通过在切点定义中使用实际的类和方法名来缩小你的执行范围。以下是经过修改的 XML 配置文件,用于展示该概念。
The above-defined <aop:pointcut> selects all the methods defined under the package com.tutorialspoint. Let us suppose, you want to execute your advice before or after a particular method, you can define your PointCut to narrow down your execution by replacing stars (*) in PointCut definition with actual class and method names. Following is a modified XML configuration file to show the concept.
<?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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Age : 11
Spring AOP - XML Based Before Advice
Before 是一种建议类型,它确保建议在方法执行之前运行。以下是 before 建议的语法。
Before is an advice type which ensures that an advice runs before the method execution. Following is the syntax of before advice.
Syntax
<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>
其中,
Where,
-
PointCut-id − id of the PointCut.
-
methodName − Method name of the function to be called before a called function.
为了理解与 Before 建议相关的上述概念,让我们编写一个示例,它将实现 Before 建议。为了编写我们带有少许建议的示例,让我们使用现成的 Eclipse IDE,并使用以下步骤来创建 Spring 应用程序。
To understand the above-mentioned concepts related to Before Advice, let us write an example, which will implement Before Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
一旦你完成了创建源文件和配置文件,就运行你的应用程序。在你的应用程序中右击 MainApp.java,并使用 run as Java Application 命令。如果你的应用程序一切正常,它将打印以下信息。
Once you are done creating source and configuration files, run your application. Right-click on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Age : 11
Spring AOP - XML Based After Advice
After 是一种建议类型,它确保建议在方法执行之后运行。以下是 after 建议的语法。
After is an advice type which ensures that an advice runs after the method execution. Following is the syntax of after advice.
Syntax
<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>
其中,
Where,
-
PointCut-id − id of the PointCut.
-
methodName − Method name of the function to be called after a called function.
为了理解与 After 建议相关的上述概念,让我们编写一个示例,它将实现 After 建议。为了编写我们带有少许建议的示例,让我们使用现成的 Eclipse IDE,并使用以下步骤来创建 Spring 应用程序。
To understand the above-mentioned concepts related to After Advice, let us write an example which will implement After Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
一旦你完成了创建源文件和配置文件,就运行你的应用程序。在你的应用程序中右击 MainApp.java,并使用 run as Java Application 命令。如果你的应用程序一切正常,这将打印以下信息。
Once you are done creating source and configuration files, run your application. Right-click on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, this will print the following message.
Name : Zara
Age : 11
Student profile setup complete.
Spring AOP - XML Based After Returning Advice
After 是一种建议类型,它确保仅在方法成功完成后,建议才会在方法执行之后运行。以下是 after 建议的语法。
After is an advice type which ensures that an advice runs after the method execution only if the method completes successfully. Following is the syntax of after advice.
Syntax
<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>
其中,
Where,
-
PointCut-id − id of the PointCut.
-
methodName − Method name of the function to be called after a called function returns successfully.
为了理解与 After Returning 建议相关的上述概念,让我们编写一个示例,它将实现 After Returning 建议。为了编写我们带有少许建议的示例,让我们使用现成的 Eclipse IDE,并使用以下步骤来创建 Spring 应用程序:
To understand the above-mentioned concepts related to After Returning Advice, let us write an example which will implement After Returning advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Name : Zara
Returning : Name
Age : 11
Exception raised
Spring AOP - XML Based After Throwing Advice
After-throwing 是一种建议类型,它确保仅在方法通过抛出异常退出时,建议才会在方法执行之后运行。以下是 after-throwing 建议的语法。
After-throwing is an advice type which ensures that an advice runs after the method execution, only if the method exits by throwing an exception. Following is the syntax of after-throwing advice.
Syntax
<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>
其中,
Where,
-
PointCut-id − id of the PointCut.
-
ex − Exception to be thrown.
-
methodName − Method name of the function to be called when a called function throws an exception and exits.
为了理解与 After Throwing Advice 相关的上述概念,让我们编写一个将实现 After Throwing Advice 的示例。为了用很少的建议编写示例,让我们使用现有的 Eclipse IDE,并按照以下步骤创建一个 Spring 应用程序 −
To understand the above-mentioned concepts related to After Throwing Advice, let us write an example which will implement After Throwing Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
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 Based Around Advice
Around 是一种通知类型,它确保一个通知在方法执行之前和之后运行。以下是 around 通知的语法。
Around is an advice type which ensures that an advice runs before and after the method execution. Following is the syntax of around advice.
Syntax
<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>
其中,
Where,
-
PointCut-id − id of the PointCut.
-
methodName − Method name of the function to be called before a called function.
为了理解与 Around Advice 相关的上述概念,让我们编写一个将实现 Around Advice 的示例。为了用很少的建议编写示例,让我们使用现有的 Eclipse IDE,并按照以下步骤创建一个 Spring 应用程序 −
To understand the above-mentioned concepts related to Around Advice, let us write an example which will implement Around Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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();
}
}
以下是配置文件 Beans.xml 。
Following is the configuration file 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.tutorialspoint.Student.getName(..))"/>
<aop:around pointcut-ref = "selectName" method = "aroundAdvice"/>
</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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Around advice
Name : Zara
Returning Zara
Spring AOP - Annotation Based Application
让我们编写一个基于注释的配置将实现通知的示例。为此,让我们使用现有的 Eclipse IDE,并按照以下步骤创建一个 Spring 应用程序。
Let us write an example which will implement advice using Annotation based configuration. For this, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.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.");
}
}
以下是 Student.java 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Going to setup student profile.
Age : 11
Spring AOP - Annotation Based PointCut
JoinPoint
结合点表示您可以插入 AOP 方面的应用程序中的一个点。您还可以说,这是使用 Spring AOP 框架将在应用程序中执行操作的实际位置。考虑以下示例 −
A JoinPoint represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. Consider the following examples −
-
All methods classes contained in a package(s).
-
A particular methods of a class.
Pointcut
切入点是一组一个或更多个结合点,应在其中执行建议。您可以使用表达式或模式指定切入点,正如我们在 AOP 示例中看到的那样。在 Spring 中,切入点有助于使用特定的结合点来应用建议。考虑以下示例 −
Pointcut is a set of one or more JoinPoint where an advice should be executed. You can specify Pointcuts using expressions or patterns as we will see in our AOP examples. In Spring, Pointcut helps to use specific JoinPoints to apply the advice. Consider the following examples −
-
@Pointcut("execution(* com.tutorialspoint..(..))")
-
@Pointcut("execution(* com.tutorialspoint.Student.getName(..))")
Syntax
@Aspect
public class Logging {
@Pointcut("execution(* com.tutorialspoint.*.*(..))")
private void selectAll(){}
}
其中,
Where,
-
@Aspect − Mark a class as a class containing advice methods.
-
@Pointcut − Mark a function as a Pointcut
-
execution( expression ) − Expression covering methods on which advice is to be applied.
为了理解与结合点和切入点相关的上述概念,让我们编写一个将实现几个切入点的示例。为了编写我们的一些建议的示例,让我们有一个正在运行的 Eclipse IDE,并使用以下步骤创建一个 Spring 应用程序 −
To understand the above-mentioned concepts related to JoinPoint and PointCut, let us write an example which will implement few of the PointCuts. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.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.");
}
}
以下是 Student.java 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Going to setup student profile.
Age : 11
上述定义的 @Pointcut 使用了一个表达式选择 com.tutorialspoint 包下定义的所有方法。@Before 增强使用了上述定义的 Pointcut 作为参数。方法 beforeAdvice() 实际上将在 Pointcut 涉及到的每个方法前被调用。
The above-defined @Pointcut uses an expression to select all the methods defined under the package com.tutorialspoint. @Before advice uses the above-defined Pointcut as a parameter. Effectively beforeAdvice() method will be called before every method covered by above Pointcut.
Spring AOP - Annotation Based Before Advice
@Before 是一种通知类型,它确保一个通知在方法执行之前运行。以下是 @Before 通知的语法。
@Before is an advice type which ensures that an advice runs before the method execution. Following is the syntax of @Before advice.
Syntax
@Pointcut("execution(* com.tutorialspoint.Student.getName(..))")
private void selectGetName(){}
@Before("selectGetName()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
其中,
Where,
-
@Pointcut − Mark a function as a Pointcut
-
execution( expression ) − Expression covering methods on which advice is to be applied.
-
@Before − Mark a function as an advice to be executed before method(s) covered by Pointcut.
为了理解与 @Before Advice 相关的上述概念,让我们编写一个将实现 @Before Advice 的示例。为了用很少的建议编写示例,让我们使用现有的 Eclipse IDE,并按照以下步骤创建一个 Spring 应用程序 −
To understand the above-mentioned concepts related to @Before Advice, let us write an example which will implement @Before Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.tutorialspoint.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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Age : 11
上面定义的 @Pointcut 使用一个表达式来选择在包 com.tutorialspoint 中的类中定义的方法 getAge() 。@After 通知使用上面定义的 Pointcut 作为参数。effectively afterAdvice() 方法将在上面 Pointcut 涵盖的每个方法之前被调用。
The above-defined @Pointcut uses an expression to select method getAge() defined in class(es) under the package com.tutorialspoint. @After advice uses the above-defined Pointcut as a parameter. Effectively afterAdvice() method will be called before every method covered by the above Pointcut.
Spring AOP - Annotation Based After Advice
@After 是一种通知类型,它确保一个通知在方法执行之后运行。以下是 @After 通知的语法。
@After is an advice type which ensures that an advice runs after the method execution. Following is the syntax of @After advice.
Syntax
@Pointcut("execution(* com.tutorialspoint.Student.getAge(..))")
private void selectGetName(){}
@After("selectGetAge()")
public void afterAdvice(){
System.out.println("Student profile setup completed.");
}
其中,
Where,
-
@Pointcut − Mark a function as a Pointcut
-
execution( expression ) − Expression covering methods on which advice is to be applied.
-
@After − Mark a function as an advice to be executed before method(s) covered by Pointcut.
为了理解与 @After Advice 相关的上述概念,让我们编写一个将实现 @After Advice 的示例。为了用很少的建议编写示例,让我们使用现有的 Eclipse IDE,并按照以下步骤创建一个 Spring 应用程序。
To understand the above-mentioned concepts related to @After Advice, let us write an example which will implement @After Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.tutorialspoint.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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Name : Zara
Age : 11
Student profile setup completed.
上面定义的 @Pointcut 使用一个表达式来选择在包 com.tutorialspoint 中的类中定义的方法 getAge() 。@After 通知使用上面定义的 Pointcut 作为参数。effectively afterAdvice() 方法将在上面 Pointcut 涵盖的每个方法之前被调用。
The above-defined @Pointcut uses an expression to select method getAge() defined in class(es) under the package com.tutorialspoint. @After advice uses the above-defined Pointcut as a parameter. Effectively afterAdvice() method will be called before every method covered by the above Pointcut.
Annotation Based After Returning Advice
@AfterReturning 是一个通知类型,它确保一个通知在方法成功执行后运行。以下是 @AfterReturning 通知的语法。
@AfterReturning is an advice type, which ensures that an advice runs after the method executes successfully. Following is the syntax of @AfterReturning advice.
Syntax
@AfterReturning(Pointcut = "execution(* com.tutorialspoint.Student.*(..))", returning = "retVal")
public void afterReturningAdvice(JoinPoint jp, Object retVal){
System.out.println("Method Signature: " + jp.getSignature());
System.out.println("Returning:" + retVal.toString() );
}
其中,
Where,
-
@AfterReturning − Mark a function as an advice to be executed before method(s) covered by Pointcut, if the method returns successfully.
-
Pointcut − Provides an expression to select a function
-
execution( expression ) − Expression covering methods on which advice is to be applied.
-
returning − Name of the variable to be returned.
为了理解与 @AfterReturning Advice 相关的上述概念,让我们编写一个将实现 @AfterReturning Advice 的示例。为了用很少的建议编写示例,让我们使用现有的 Eclipse IDE,并按照以下步骤创建一个 Spring 应用程序。
To understand the above-mentioned concepts related to @AfterReturning Advice, let us write an example, which will implement @AfterReturning Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.tutorialspoint.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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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.getAge();
}
}
以下是配置文件 Beans.xml 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Age : 11
Method Signature: Integer com.tutorialspoint.Student.getAge()
Returning 11
Spring AOP - Annotation Based After Throwing Advice
@AfterThrowing 是一种通知类型,它确保在方法抛出一个异常时运行一个通知。以下是 @AfterThrowing 通知的语法。
@AfterThrowing is an advice type which ensures that an advice runs if the method throws an exception. Following is the syntax of @AfterThrowing advice.
Syntax
@AfterThrowing(Pointcut = "execution(* com.tutorialspoint.Student.*(..))", throwing = "error")
public void afterThrowingAdvice(JoinPoint jp, Throwable error){
System.out.println("Method Signature: " + jp.getSignature());
System.out.println("Exception: "+error);
}
其中,
Where,
-
@AfterThrowing − Mark a function as an advice to be executed before method(s) covered by Pointcut, if the method throws an exception.
-
Pointcut − Provides an expression to select a function.
-
execution( expression ) − Expression covering methods on which advice is to be applied.
-
throwing − Name of the exception to be returned.
为了理解与 @AfterThrowing 相关建议已经提到的概念,我们来写一个将实施 @AfterThrowing 建议的示例。若要使用少量的建议来编写示例,我们先来设置一个可行的 Eclipse IDE,然后使用以下步骤来创建一个 Spring 应用程序:
To understand the above-mentioned concepts related to @AfterThrowing Advice, let us write an example which will implement @AfterThrowing Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.tutorialspoint.Student.*(..))", throwing = "error")
public void afterThrowingAdvice(JoinPoint jp, Throwable error){
System.out.println("Method Signature: " + jp.getSignature());
System.out.println("Exception: "+error);
}
}
以下是 Student.java 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Exception raised
Method Signature: void com.tutorialspoint.Student.printThrowException()
Exception: java.lang.IllegalArgumentException
Exception in thread "main" java.lang.IllegalArgumentException
at com.tutorialspoint.Student.printThrowException(Student.java:25)
...
Spring AOP - Annotation Based Around Advice
@Around 是建议类型,它确保建议可以在方法执行前后运行。以下是 @Around 建议的语法:
@Around is an advice type, which ensures that an advice can run before and after the method execution. Following is the syntax of @Around advice.
Syntax
@Pointcut("execution(* com.tutorialspoint.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();
}
其中,
Where,
-
@Pointcut − Mark a function as a Pointcut
-
execution( expression ) − Expression covering methods on which advice is to be applied.
-
@Around − Mark a function as an advice to be executed before method(s) covered by Pointcut.
为了理解与 @Around 相关建议已经提到的概念,我们来写一个将实施 @Around 建议的示例。若要使用少量的建议来编写示例,我们先来设置一个可行的 Eclipse IDE,然后使用以下步骤来创建一个 Spring 应用程序:
To understand the above-mentioned concepts related to @Around Advice, let us write an example which will implement @Around Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.tutorialspoint.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 文件的内容。
Following is the content of the Student.java file.
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 文件的内容。
Following is the content of the MainApp.java file.
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.getAge();
}
}
以下是配置文件 Beans.xml 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Around advice
Age : 11
Returning 11
Spring AOP - Proxy
到目前为止,我们已经使用 <aop:config> 或 < aop:aspectj-autoproxy> 声明了方面。我们可以以编程方式创建代理,也可以使用代理对象以编程方式调用方面。
So far, we’ve declared aspects using <aop:config> or < aop:aspectj-autoproxy>. We can create a proxy programmatically as well as invoke the aspects programmatically using the proxy object.
Syntax
//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();
其中,
Where,
-
AspectJProxyFactory − Factory class to create a proxy object.
-
Logging.class − Class of the Aspect containing advices.
-
Student − Business class to be advised.
为了理解与代理相关的上述概念,我们来写一个将实施代理的示例。若要使用少量的建议来编写示例,我们先来设置一个可行的 Eclipse IDE,然后使用以下步骤来创建一个 Spring 应用程序:
To understand the above-mentioned concepts related to proxy, let us write an example which will implement proxy. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.tutorialspoint.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 文件的内容。
Following is the content of the Student.java file.
package com.tutorialspoint;
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 文件的内容。
Following is the content of the MainApp.java file.
package com.tutorialspoint;
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 。
Following is the configuration file 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.tutorialspoint.Student">
<property name = "age" value = "11"/>
</bean>
<!-- Definition for logging aspect -->
<bean id = "logging" class = "com.tutorialspoint.Logging"/>
</beans>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Age : 11
Spring AOP - Custom Annotation
根据切入点表达式,它们可能会应用于不适用于此建议的其他 Bean。例如,考虑以下表达式。
As per Pointcut expressions, it may be the case that they get applied to some other beans for which advice is not intended. For example, consider the following expression.
execution(* com.tutorialspoint.*.getAge(..))
将添加 getAge() 方法的新 Spring Bean,并且建议将开始应用于它,即使它可能不是预期的。为实现此目的,我们可以创建一个自定义注释并注释应用建议的方法。
A new spring bean is added with getAge() method and the advice will start getting applied to it although it may not be intended. To achieve this, we can create a custom annotation and annotate the methods on which the advice is to be applied.
@Before("@annotation(com.tutorialspoint.Loggable)")
为了理解与 @Before 相关建议已经提到的概念,我们来写一个将实施 @Before 建议的示例。若要使用少量的建议来编写示例,我们先来设置一个可行的 Eclipse IDE,然后使用以下步骤来创建一个 Spring 应用程序。
To understand the above-mentioned concepts related to @Before Advice, let us write an example which will implement @Before Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
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 文件的内容。这实际上是方面模块的一个示例,它定义了在各个点调用的方法。
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
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.tutorialspoint.Loggable)")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
}
以下是 Loggable.java 文件的内容:
Following is the content of the Loggable.java file −
package com.tutorialspoint;
public @interface Loggable {
}
以下是 Student.java 文件的内容。
Following is the content of the Student.java file.
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;
}
@Loggable
public String getName() {
System.out.println("Name : " + name );
return name;
}
public void printThrowException(){
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
以下是 MainApp.java 文件的内容。
Following is the content of the MainApp.java file.
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 。
Following is the configuration file 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>
Run Project
创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Age : 11