AOP basé sur @AspectJ avec Spring

@AspectJ fait référence à un style de déclaration d'aspects en tant que classes Java régulières annotées avec des annotations Java 5. La prise en charge de @AspectJ est activée en incluant l'élément suivant dans votre fichier de configuration basé sur un schéma XML.

<aop:aspectj-autoproxy/>

Vous aurez également besoin des bibliothèques AspectJ suivantes sur le chemin de classe 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

Les classes Aspects sont comme n'importe quel autre bean normal et peuvent avoir des méthodes et des champs comme n'importe quelle autre classe, sauf qu'elles seront annotées avec @Aspect comme suit -

package org.xyz;

import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AspectModule {
}

Ils seront configurés en XML comme tout autre bean comme suit -

<bean id = "myAspect" class = "org.xyz.AspectModule">
   <!-- configure properties of aspect here as normal -->
</bean>

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 @ AspectJ, la déclaration de coupe de point comporte deux parties -

  • Une expression ponctuelle qui détermine exactement les exécutions de méthode qui nous intéressent.

  • Une signature ponctuelle comprenant un nom et un nombre quelconque de paramètres. Le corps réel de la méthode n'est pas pertinent et devrait en fait être vide.

L'exemple suivant définit un pointcut nommé 'businessService' qui correspondra à l'exécution de chaque méthode disponible dans les classes sous le package com.xyz.myapp.service -

import org.aspectj.lang.annotation.Pointcut;

@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression 
private void businessService() {}  // signature

L'exemple suivant définit un pointcut nommé 'getname' qui correspondra à l'exécution de la méthode getName () disponible dans la classe Student sous le package com.tutorialspoint -

import org.aspectj.lang.annotation.Pointcut;

@Pointcut("execution(* com.tutorialspoint.Student.getName(..))") 
private void getname() {}

Déclarer des conseils

Vous pouvez déclarer l'un des cinq conseils en utilisant les annotations @ {ADVICE-NAME} comme indiqué dans l'extrait de code. Cela suppose que vous ayez déjà défini une méthode de signature par pointillé businessService () -

@Before("businessService()")
public void doBeforeTask(){
   ...
}

@After("businessService()")
public void doAfterTask(){
   ...
}

@AfterReturning(pointcut = "businessService()", returning = "retVal")
public void doAfterReturnningTask(Object retVal) {
   // you can intercept retVal here.
   ...
}

@AfterThrowing(pointcut = "businessService()", throwing = "ex")
public void doAfterThrowingTask(Exception ex) {
  // you can intercept thrown exception here.
  ...
}

@Around("businessService()")
public void doAroundTask(){
   ...
}

Vous pouvez définir un point de coupe en ligne pour n'importe lequel des conseils. Voici un exemple pour définir la coupe de point en ligne pour le conseil avant -

@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
   ...
}

Exemple d'AOP basé sur @AspectJ

Pour comprendre les concepts mentionnés ci-dessus liés à l'AOP basé sur @AspectJ, é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 -

Pas 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 à divers points.

package com.tutorialspoint;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;

@Aspect
public class Logging {
   /** Following is the definition for a pointcut to select
      *  all the methods available. So advice will be called
      *  for all the methods.
   */
   @Pointcut("execution(* com.tutorialspoint.*.*(..))")
   private void selectAll(){}

   /** 
      * This is the method which I would like to execute
      * before a selected method execution.
   */
   @Before("selectAll()")
   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.
   */
   @After("selectAll()")
   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.
   */
   @AfterReturning(pointcut = "selectAll()", returning = "retVal")
   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 by any method.
   */
   @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
   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:aspectj-autoproxy/>

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