AOP basé sur un schéma XML avec Spring

Pour utiliser les balises d'espace de noms AOP décrites dans cette section, vous devez importer le schéma springAOP comme décrit -

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

Vous aurez également besoin des bibliothèques AspectJ suivantes sur le CLASSPATH de votre application. Ces bibliothèques sont disponibles dans le répertoire 'lib' d'une installation AspectJ, sinon vous pouvez les télécharger depuis Internet.

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

Déclarer un aspect

Un aspect est déclaré en utilisant le <aop:aspect> élément, et le bean de support est référencé à l'aide de ref attribut comme suit -

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

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

Ici, "aBean" sera configuré et la dépendance injectée comme n'importe quel autre bean Spring comme vous l'avez vu dans les chapitres précédents.

Déclarer une coupe de point

UNE pointcutaide à déterminer les points de jonction (c'est-à-dire les méthodes) d'intérêt à exécuter avec différents conseils. Lorsque vous travaillez avec une configuration basée sur un schéma XML, le pointcut sera défini comme suit -

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

L'exemple suivant définit un pointcut nommé 'businessService' qui correspondra à l'exécution de la méthode getName () disponible dans la classe Student sous le 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>

Déclarer des conseils

Vous pouvez déclarer l'un des cinq conseils à l'intérieur d'un <aop: aspect> en utilisant l'élément <aop: {ADVICE NAME}> comme indiqué ci-dessous -

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

Vous pouvez utiliser le même doRequiredTaskou différentes méthodes pour différents conseils. Ces méthodes seront définies dans le cadre du module aspect.

Exemple d'AOP basé sur un schéma XML

Pour comprendre les concepts mentionnés ci-dessus liés à l'AOP basé sur un schéma XML, écrivons un exemple qui implémentera quelques-uns des conseils. Pour écrire notre exemple avec quelques conseils, mettons en place un IDE Eclipse fonctionnel et suivez les étapes suivantes pour créer une application Spring -

Étape La description
1 Créez un projet avec un nom SpringExample et créez un package com.tutorialspoint sous lesrc dossier dans le projet créé.
2 Ajoutez les bibliothèques Spring requises à l'aide de l' option Ajouter des JAR externes comme expliqué dans le chapitre Exemple de Spring Hello World .
3 Ajouter des bibliothèques spécifiques à Spring AOP aspectjrt.jar, aspectjweaver.jar et aspectj.jar dans le projet.
4 Créer des classes Java Logging, Student et MainApp sous le package com.tutorialspoint .
5 Créez le fichier de configuration Beans Beans.xml sous lesrc dossier.
6 La dernière étape consiste à créer le contenu de tous les fichiers Java et le fichier de configuration Bean et à exécuter l'application comme expliqué ci-dessous.

Voici le contenu de Logging.javafichier. Il s'agit en fait d'un exemple de module d'aspect qui définit les méthodes à appeler en différents 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.");
   }
   
   /** 
      * 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());   
   }
}

Voici le contenu de la Student.java fichier

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

Voici le contenu de la MainApp.java fichier

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

Voici le fichier de configuration 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>

Une fois que vous avez terminé de créer les fichiers de configuration source et bean, laissez-nous exécuter l'application. Si tout va bien avec votre application, elle imprimera le message suivant -

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

Le <aop: pointcut> défini ci-dessus sélectionne toutes les méthodes définies sous le package com.tutorialspoint. Supposons que vous souhaitiez exécuter votre conseil avant ou après une méthode particulière, vous pouvez définir votre coupe de point pour affiner votre exécution en remplaçant les étoiles (*) dans la définition de coupe par les noms réels de la classe et de la méthode. Voici un fichier de configuration XML modifié pour montrer le 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: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 vous exécutez l'exemple d'application avec ces modifications de configuration, il imprimera le message suivant -

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