AOP basado en esquemas XML con Spring

Para utilizar las etiquetas de espacio de nombres AOP descritas en esta sección, debe importar el esquema springAOP como se describe:

<?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>

También necesitará las siguientes bibliotecas AspectJ en CLASSPATH de su aplicación. Estas bibliotecas están disponibles en el directorio 'lib' de una instalación de AspectJ; de lo contrario, puede descargarlas de Internet.

  • aspectjrt.jar
  • aspectjweaver.jar
  • aspectj.jar
  • aopalliance.jar

Declarar un aspecto

Un aspect se declara usando el <aop:aspect> elemento, y se hace referencia al bean de respaldo utilizando el ref atributo de la siguiente manera -

<aop:config>
   <aop:aspect id = "myAspect" ref = "aBean">
      ...
   </aop:aspect>
</aop:config>

<bean id = "aBean" class = "...">
   ...
</bean>

Aquí se configurará "aBean" y se inyectará la dependencia como cualquier otro bean Spring como ha visto en los capítulos anteriores.

Declarar un pointcut

UN pointcutayuda a determinar los puntos de unión (es decir, los métodos) de interés que se ejecutarán con diferentes consejos. Mientras trabaja con la configuración basada en XML Schema, pointcut se definirá de la siguiente manera:

<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>

El siguiente ejemplo define un punto de acceso llamado 'businessService' que coincidirá con la ejecución del método getName () disponible en la clase Student en el paquete 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>

Declarar consejos

Puede declarar cualquiera de los cinco consejos dentro de un <aop: aspecto> utilizando el elemento <aop: {NOMBRE DEL CONSEJO}> como se indica a continuación

<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>

Puedes usar lo mismo doRequiredTasko diferentes métodos para diferentes consejos. Estos métodos se definirán como parte del módulo de aspectos.

Ejemplo de AOP basado en esquemas XML

Para comprender los conceptos mencionados anteriormente relacionados con AOP basado en esquemas XML, escribamos un ejemplo que implementará algunos de los consejos. Para escribir nuestro ejemplo con algunos consejos, tengamos un IDE de Eclipse en funcionamiento y sigamos los siguientes pasos para crear una aplicación Spring:

Paso Descripción
1 Cree un proyecto con un nombre SpringExample y cree un paquete com.tutorialspoint bajo elsrc carpeta en el proyecto creado.
2 Agregue las bibliotecas Spring requeridas usando la opción Agregar JAR externos como se explica en el capítulo Ejemplo de Spring Hello World .
3 Agregar bibliotecas específicas de Spring AOP aspectjrt.jar, aspectjweaver.jar y aspectj.jar en el proyecto.
4 Crea clases de Java Logging, Student y MainApp en el paquete com.tutorialspoint .
5 Cree el archivo de configuración de Beans Beans.xml bajo elsrc carpeta.
6 El paso final es crear el contenido de todos los archivos Java y el archivo de configuración de Bean y ejecutar la aplicación como se explica a continuación.

Aquí está el contenido de Logging.javaarchivo. Esto es en realidad una muestra del módulo de aspecto que define los métodos que se llamarán en varios puntos.

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

A continuación se muestra el contenido de la Student.java archivo

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

A continuación se muestra el contenido de la MainApp.java archivo

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

A continuación se muestra el archivo de configuración 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>

Una vez que haya terminado de crear los archivos de configuración de fuente y bean, ejecutemos la aplicación. Si todo está bien con su aplicación, imprimirá el siguiente mensaje:

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
.....
other exception content

El <aop: pointcut> definido anteriormente selecciona todos los métodos definidos en el paquete com.tutorialspoint. Supongamos que desea ejecutar su consejo antes o después de un método en particular, puede definir su pointcut para reducir su ejecución reemplazando estrellas (*) en la definición de pointcut con los nombres reales de clase y método. A continuación se muestra un archivo de configuración XML modificado para mostrar el concepto:

<?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: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>

Si ejecuta la aplicación de muestra con estos cambios de configuración, imprimirá el siguiente mensaje:

Going to setup student profile.
Name : Zara
Student profile has been setup.
Age : 11
Exception raised
.....
other exception content