Springaop 简明教程

Spring AOP - XML Based Application

在本章中,我们将使用 Spring AOP 框架编写实际的 AOP 应用程序。在开始使用 Spring-WS 框架编写第一个示例之前,您必须确保已按照 Spring Web Services - Environment Setup 章节中的说明正确设置 Spring AOP 环境。

现在,继续编写一个简单的基于控制台的 Spring AOP 应用程序,该应用程序将演示 AOP 概念。

Create a Project

Step 1 − 打开命令控制台,转到 C:\MVN 目录并执行以下 mvn 命令。

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

Maven 将开始处理并将创建完整的 Java 应用程序项目结构。

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: package, Value: com.tutorialspoint
[INFO] Parameter: groupId, Value: com.tutorialspoint
[INFO] Parameter: artifactId, Value: Student
[INFO] Parameter: packageName, Value: com.tutorialspoint
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\Student
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  13.388 s
[INFO] Finished at: 2021-12-27T20:18:26+05:30
[INFO] ------------------------------------------------------------------------

Step 2 − 转到 C:/MVN 目录。您将看到一个 Java 应用程序项目已创建,名为 student(如 artifactId 中指定)。更新 POM.xml 以包括 Spring-AOP 依赖项。添加 MainApp.java、Student.java 和 Logging.java 文件。

POM.xml

<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>Student</artifactId>
   <packaging>jar</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>Student</name>
   <url>http://maven.apache.org</url>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <maven.compiler.source>1.7</maven.compiler.source>
      <maven.compiler.target>1.7</maven.compiler.target>
   </properties>

   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.11</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aop</artifactId>
         <version>5.3.14</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>5.3.14</version>
      </dependency>
      <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjweaver</artifactId>
         <version>1.9.7</version>
      </dependency>
   </dependencies>
</project>

以下是 Logging.java 文件的内容。

package com.tutorialspoint;

public class Logging {
   /**
      * This is the method which I would like to execute
      * before a selected method execution.
   */
   public void beforeAdvice() {
      System.out.println("Going to setup student profile.");
   }
   /**
      * This is the method which I would like to execute
      * after a selected method execution.
   */
   public void afterAdvice() {
      System.out.println("Student profile has been setup.");
   }
   /**
      * This is the method which I would like to execute
      * when any method returns.
   */
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }
   /**
      * This is the method which I would like to execute
      * if there is an exception raised.
   */
   public void AfterThrowingAdvice(IllegalArgumentException ex) {
      System.out.println("There has been an exception: " + ex.toString());
   }
}

以下是 Student.java 文件的内容。

package com.tutorialspoint;

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

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }
   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

以下是 MainApp.java 文件的内容。

package com.tutorialspoint;

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

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

      Student student = (Student) context.getBean("student");
      student.getName();
      student.getAge();
      student.printThrowException();
   }
}

Step 3 − 在 src > main > resources 文件夹下添加 Beans.xml 配置文件。

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

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

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

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

Step 4 − 打开命令控制台,转到 C:\MVN 目录并执行以下 mvn 命令。

C:\MVN>Student> mvn package

Maven 将开始处理和下载所需的库。

C:\MVN\Student>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< com.tutorialspoint:Student >---------------------
[INFO] Building Student 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Student ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Student ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ Student ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\MVN\Student\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ Student ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ Student ---
[INFO] Surefire report directory: C:\MVN\Student\target\surefire-reports

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

Results :

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

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ Student ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.213 s
[INFO] Finished at: 2021-12-27T20:42:00+05:30
[INFO] ------------------------------------------------------------------------
C:\MVN\Student>

Import Project in Eclipse

Step 1 − 打开 Eclipse。

Step 2 − 选择 File → Import → 选项。

Step 3 − 选择 Maven 项目选项。单击“下一步”按钮。

Step 4 − 选择项目位置,即使用 Maven 创建 Student 项目的位置。

Step 5 − 单击“完成”按钮。

Run Project

创建源和配置文件后,运行您的应用程序。在应用程序中右键单击 MainApp.java 并使用 run as Java Application 命令。如果您的应用程序一切正常,它将打印以下消息。

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