鍍金池/ 教程/ Java/ Spring AOP基于XML的應(yīng)用程序
Spring AOP基于XML的After Advice
Spring AOP基于XML的Before Advice
Spring AOP基于XML的After Returning Advice
Spring AOP基于注解的切入點(diǎn)
Spring AOP基于XML的After Throwing Advice
Spring AOP實(shí)現(xiàn)
Spring AOP基于注解的Around通知
Spring AOP環(huán)境安裝設(shè)置
Spring AOP自定義注解
Spring AOP代理
Spring AOP基于XML的切入點(diǎn)
Spring AOP基于XML的Around Advice
Spring AOP通知類型
Spring AOP基于XML的應(yīng)用程序
Spring AOP基于注解的After Advice
Spring AOP基于注解的Before Advice
Spring AOP基于注解的AfterThrowing
Spring AOP教程
Spring AOP基于注解的After Returning Advice
Spring AOP核心概念
Spring AOP基于注解的應(yīng)用

Spring AOP基于XML的應(yīng)用程序

從這篇文章開始,我們使用Spring-AOP框架編寫實(shí)際的AOP應(yīng)用程序。在開始使用Spring-WS框架編寫第一個(gè)示例之前,必須確保已經(jīng)按照Spring AOP安裝配置教程中的說明正確設(shè)置了Spring-AOP開發(fā)運(yùn)行環(huán)境。

現(xiàn)在我們繼續(xù)來編寫一個(gè)簡(jiǎn)單的基于控制臺(tái)的Spring AOP應(yīng)用程序,它用于演示AOP的概念。

先來看看要?jiǎng)?chuàng)建的項(xiàng)目的目錄結(jié)構(gòu) -

創(chuàng)建項(xiàng)目

打開命令控制臺(tái),進(jìn)入D:\MVN目錄并執(zhí)行下面的mvn命令。

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

上面命令執(zhí)行后,Maven將開始處理,并將創(chuàng)建完整的java應(yīng)用程序項(xiàng)目結(jié)構(gòu)。您可能會(huì)看到一堆下載的東西,但是不要驚慌,耐心等待下載和構(gòu)建完成,如下所示 -

Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar (5 KB at 7.7 KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: D:\mvn
[INFO] Parameter: package, Value: com.yiibai
[INFO] Parameter: groupId, Value: com.yiibai
[INFO] Parameter: artifactId, Value: Student
[INFO] Parameter: packageName, Value: com.yiibai
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: D:\mvn\Student
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 09:20 min
[INFO] Finished at: 2017-04-12T03:05:53+08:00
[INFO] Final Memory: 14M/99M
[INFO] ------------------------------------------------------------------------

D:\mvn>

現(xiàn)在打開C:\MVN目錄。您將看到一個(gè)名為student的java應(yīng)用程序項(xiàng)目(在artifactId中指定)。更新POM.xml以包含Spring-AOP依賴關(guān)系。添加MainApp.java,Student.javaLogging.java這幾個(gè)代碼文件。

文件 - POM.xml 的內(nèi)容如下 -

<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.yiibai</groupId>
   <artifactId>Student</artifactId>
   <packaging>jar</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>Student</name>
   <url>http://maven.apache.org</url>
   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aop</artifactId>
         <version>4.1.0.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>4.1.4.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjweaver</artifactId>
         <version>1.6.8</version>
      </dependency>
   </dependencies>
</project>

文件 - Logging.java 的內(nèi)容如下 -

package com.yiibai;

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 的內(nèi)容如下 -

package com.yiibai;

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 的內(nèi)容如下 -

package com.yiibai;

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();
   }
}

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.yiibai.*.*(..))"/>
         <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.yiibai.Student">
      <property name="name"  value="Maxsu" />
      <property name="age"  value="21"/>      
   </bean>

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

</beans>

打開命令控制臺(tái),進(jìn)入D:\MVN目錄并執(zhí)行下面的mvn命令。

D:\MVN>Student> mvn package

Maven將開始處理并下載所需的庫。

Downloading: http://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.jar
Downloading: http://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0/plexus-utils-3.0.jar
Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/maven-archiver/2.5/maven-archiver-2.5.jar (22 KB at 25.9 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-io/2.0.2/plexus-io-2.0.2.jar (57 KB at 54.3 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.jar (203 KB at 188.7 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0/plexus-utils-3.0.jar (221 KB at 145.8 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-archiver/2.1/plexus-archiver-2.1.jar (181 KB at 100.8 KB/sec)
[INFO] Building jar: D:\mvn\Student\target\Student-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 43.164 s
[INFO] Finished at: 2017-04-12T05:11:44+08:00
[INFO] Final Memory: 19M/158M
[INFO] ------------------------------------------------------------------------

D:\mvn\Student>

在Eclipse中導(dǎo)入項(xiàng)目

打開Eclipse IDE,導(dǎo)入項(xiàng)目目錄。

選擇文件>導(dǎo)入>選項(xiàng)
選擇Maven項(xiàng)目選項(xiàng)。點(diǎn)擊下一步按鈕。
選擇項(xiàng)目位置,其中使用Maven創(chuàng)建Student項(xiàng)目。
單擊完成按鈕。

運(yùn)行項(xiàng)目

完成創(chuàng)建源代碼和配置文件后,運(yùn)行應(yīng)用程序。 右鍵單擊應(yīng)用程序中的MainApp.java,并使用運(yùn)行方式作為Java應(yīng)用程序命令。 如果您的應(yīng)用程序沒有問題,將打印以下消息:

四月 12, 2017 5:19:04 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Apr 12 05:19:04 CST 2017]; root of context hierarchy
四月 12, 2017 5:19:04 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [Beans.xml]
Going to setup student profile.
Exception in thread "main" Name : Maxsu
Student profile has been setup.
Returning:Maxsu
Going to setup student profile.
Age : 21
Student profile has been setup.
Returning:21
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
java.lang.IllegalArgumentException
    at com.yiibai.Student.printThrowException(Student.java:25)
    at com.yiibai.Student$$FastClassBySpringCGLIB$$e9280b4b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:43)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
    at com.yiibai.Student$$EnhancerBySpringCGLIB$$92ccc3c2.printThrowException(<generated>)
    at com.yiibai.MainApp.main(MainApp.java:16)