Spring 基于XML配置的AOP

  • 基于XML的面向切面编程(AOP)

    要使用本节中描述的AOP名称空间标签,您需要按照以下描述导入springAOP模式
    <?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>
    
    您还将在应用程序的CLASSPATH上需要以下AspectJ库。这些库位于AspectJ源码包的'lib'目录中,您可以从网络上下载它们。
    • Aspectjrt.jar
    • Aspectjweaver.jar
    • Aspectj.jar
    • aopalliance.jar
  • 声明切面

    使用<aop:aspect>元素声明一个切面,并使用ref属性引用后备bean ,如下所示:
    <aop:config>
       <aop:aspect id = "myAspect" ref = "aBean">
          ...
       </aop:aspect>
    </aop:config>
    
    <bean id = "aBean" class = "...">
       ...
    </bean>
    就像在前面的章节中看到的那样,在这里将配置“aBean”并注入依赖项。
  • 声明切入点

    一个切入点有助于确定插入点(即方法)以不同的active来执行的加入。在使用基于XML的配置时,切入点将定义如下
    <aop:config>
       <aop:aspect id = "myAspect" ref = "aBean">
          <aop:pointcut id = "businessService" 
             expression = "execution(*com.xyz.myapp.service.*.*(..))"/>
             ...
       </aop:aspect>
    </aop:config>
    
    <bean id = "aBean" class = "...">
       ...
    </bean>
    以下示例定义了一个名为'businessService'的切入点,该切入点将匹配com.jc2182包下Student类中可用的getName()方法的执行-
    <aop:config>
       <aop:aspect id = "myAspect" ref = "aBean">
          <aop:pointcut id = "businessService" 
             expression = "execution(*com.jc2182.Student.getName(..))"/>
             ...
       </aop:aspect>
    </aop:config>
    
    <bean id = "aBean" class = "...">
       ...
    </bean>
  • 定义通知

    您可以使用<aop:{ADVICE NAME}>元素在<aop:aspect>中声明五个通知中的任何一个,如下所示
    <aop:config>
       <aop:aspect id = "myAspect" ref = "aBean">
          <aop:pointcut id = "businessService"
             expression = "execution(* com.xyz.myapp.service.*.*(..))"/>
    
          <!-- a before advice definition -->
          <aop:before pointcut-ref = "businessService" method = "doRequiredTask"/>
    
          <!-- an after advice definition -->
          <aop:after pointcut-ref = "businessService" method = "doRequiredTask"/>
    
          <!-- an after-returning advice definition -->
          <!--The doRequiredTask method must have parameter named retVal -->
          <aop:after-returning pointcut-ref = "businessService"
             returning = "retVal" method = "doRequiredTask"/>
    
          <!-- an after-throwing advice definition -->
          <!--The doRequiredTask method must have parameter named ex -->
          <aop:after-throwing pointcut-ref = "businessService"
             throwing = "ex" method = "doRequiredTask"/>
    
          <!-- an around advice definition -->
          <aop:around pointcut-ref = "businessService" method = "doRequiredTask"/>
          ...
       </aop:aspect>
    </aop:config>
    
    <bean id = "aBean" class = "...">
      ...
    </bean>
    您可以将相同的doRequiredTask或不同的方法用于不同的通知。这些方法将定义为Aspect模块的一部分。
  • 基于XML模式的AOP示例

    为了理解与基于XML Schema的AOP相关的上述概念,让我们编写一个示例,该示例将实现一些通知。
    假设拥有一个运行良好的Eclipse IDE,并采取以下步骤来创建Spring应用程序-
    1. 创建一个名称为SpringExample的项目,并在创建的项目的src文件夹下创建一个包com.jc2182。
    2. 使用“添加外部JAR”选项添加所需的Spring库,如“Spring Hello World示例”一章中所述。
    3. 在项目中添加特定于Spring AOP的库Aspectjrt.jar,aspectjweaver.jar和Aspectj.jar。
    4. 在com.jc2182包下创建Java类Logging,Student和MainApp。
    5. 在src文件夹下创建Beans配置文件Beans.xml。
    6. 最后一步是创建所有Java文件和Bean配置文件的内容,然后按以下说明运行应用程序。
    这是Logging.java文件的内容。这实际上是Aspect模块的一个示例,它定义了要在各个点调用的方法。
    package com.jc2182;
    
    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.jc2182;
    
    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.jc2182;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MainApp {
       public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
          
          Student student = (Student) context.getBean("student");
          student.getName();
          student.getAge();
          student.printThrowException();
       }
    }  
    
    以下是配置文件Beans.xml
    
    package com.jc2182;
    
    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();
       }
    }  
    
    完成创建源和Bean配置文件后,让我们运行该应用程序。如果您的应用程序一切正常,它将显示以下类似消息:
    
    Going to setup student profile.
    Name : Zara
    Student profile has been setup.
    Returning:Zara
    Going to setup student profile.
    Age : 11
    Student profile has been setup.
    Returning:11
    Going to setup student profile.
    Exception raised
    Student profile has been setup.
    There has been an exception: java.lang.IllegalArgumentException
    Exception in thread "main" java.lang.IllegalArgumentException
      at com.jc2182.Student.printThrowException(Student.java:23)
      at com.jc2182.Student$FastClassBySpringCGLIB$f4af5e6c.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.jc2182.Student$EnhancerBySpringCGLIB$8caabfb1.printThrowException(<generated>)
      at com.jc2182.MainApp.main(MainApp.java:13)  
    
    上面定义的<aop:pointcut>选择在com.jc2182包下定义的所有方法。让我们假设,要在特定方法之前或之后执行通知,可以定义切入点以通过用实际的类和方法名称替换切入点定义中的星号(*)来缩小执行范围。以下是修改后的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.jc2182.Student.getName(..))"/>
             <aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>
             <aop:after pointcut-ref = "selectAll" method = "afterAdvice"/>
          </aop:aspect>
       </aop:config>
    
       <!-- Definition for student bean -->
       <bean id = "student" class = "com.jc2182.Student">
          <property name = "name" value = "Zara" />
          <property name = "age" value = "11"/>      
       </bean>
    
       <!-- Definition for logging aspect -->
       <bean id = "logging" class = "com.jc2182.Logging"/> 
          
    </beans>  
    
    如果使用这些配置更改执行示例应用程序,它将打印以下消息
    
    Going to setup student profile.
    Name : Zara
    Student profile has been setup.
    Age : 11
    Exception raised
    Exception in thread "main" java.lang.IllegalArgumentException
      at com.jc2182.Student.printThrowException(Student.java:23)
      at com.jc2182.Student$FastClassBySpringCGLIB$f4af5e6c.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.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.jc2182.Student$EnhancerBySpringCGLIB$eb53a2ad.printThrowException(<generated>)
      at com.jc2182.MainApp.main(MainApp.java:13)