English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

SpringBoot AOP @AfterThrowing

After throwing est un type de conseil dans Spring AOP. Si une méthode lève une exception, il assure que le conseil s'exécute. Nous utilisons @AfterThrowing Annoter pour réaliser le conseil après le lancement.

Syntaxe:

@AfterThrowing(PointCut="execution(expression)", throwing="name")

Où:

PointCut: Choisissez une fonction.

execution(expression):

after throwing: Nom de l'exception à renvoyer.

Permettons d'implémenter after dans notre application.-conseil après le lancement.

Exemple Spring Boot @AfterThrowing

Nous utiliserons l'exemple précédent dans cette section. Vous pouvez télécharger le projet ou apporter des modifications à l'exemple précédent.

步骤1: Ouvrir Spring Initializr http://start.spring.io .

Le2Étape: Fourni GroupeNom. Nous avons fourni le nom de groupe com.w3codebox。

步骤3: Fourni Artifact Id。Fournir Artifact Id aop-after-throwing-advice-example.。

步骤4: ajouter Spring Web dépendances。

步骤5: cliquez Générerbouton. Lorsque nous cliquons sur le bouton "Générer", il enveloppe toutes les spécifications dans jar le fichier et le télécharger sur le système local.

步骤6: Extraire

Le7Étape: ImporterDossier, veuillez suivre les étapes suivantes:

Fichier-> Importer- > Existant projet Maven-> Suivant-> Parcourir le dossier aop-throwing-advice-example -> Fini。

步骤8: 打开 pom.xml 文件,并添加以下 AOP 依赖项。它是使用 Spring AOP et AspectJ 开始学习面向方面编程。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.w3codebox</groupId>
<artifactId>aop-after-throwing-advice-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>aop-after-throwing-advice-example</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

步骤9: Dans src/main/java dossier Créer un nom appelé com.w3codebox.model dans codebox.model.

步骤10: dans le paquet com.w3Créer un paquet nommé Account de la classe.

Dans la classe "Compte", effectuez les opérations suivantes:

Défini deux variables de type String accountNumber et accountType . Cliquez-droit sur Fichier -> Source-> Utiliser les champs pour générer le constructeur Générer Getters。
Cliquez-droit sur Fichier-> Source-> Générer Getters et Setters-> Sélectionner Getters-> Générer
Générer toString()
Cliquez-droit sur le fichier-> Source-> Générer toString()

Account.java

package com.w3codebox.model;
public class Account 
{
private String accountNumber;
private String accountType;
public Account(String accountNumber, String accountType) 
{
super();
this.accountNumber = accountNumber;
this.accountType = accountType;
}
public String getAccountType() 
{
return accountType;
}
public String getAccountNumber() 
{
return accountNumber;
}
@Override
public String toString()
{
return "Account [accountNumber=" + accountNumber+ ", accountType=" + accountType + "]";
}
}

步骤11: Créer un autre nom appelé com.w3codebox.service.impl du paquet.

步骤12: Dans ce paquetage, créer un nom appelé La classe AccountServiceImple.

Dans cette classe, nous définissons le service de compte.

AccountServiceImpl.Java

package com.w3codebox.service.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.w3codebox.model.Account;
@Service
public class AccountServiceImpl implements AccountService 
{
//storing account detail in the HashMap
private static Map<String, Account> map = null;
static
{
map = new HashMap<>();
//adding account detail in the map
map.put("M4546779, new Account("10441117000", "Saving Account");
map.put("K2434567, new Account("10863554577, "Current Account");
}
@Override
public Account getAccountByCustomerId(String customerId) throws Exception
{
if(customerId == null)
{
throw new Exception("Invalid! Customer Id");
}
Account account = null;
Set<Entry<String, Account>> entrySet = map.entrySet();
for (Entry<String, Account> entry : entrySet) 
{
if(entry.getKey().equals(customerId))
{
account = entry.getValue();
}
}
return account;
}
}

步骤13: dans le paquet com.w3codebox.service.impl。 dans la création d'une classe nommée AccountService 的接口。

AccountService.java

package com.w3codebox.service.impl;
import com.w3codebox.model.Account;
//creating interface that throws exception if the customer id not found 
public interface AccountService 
{
public abstract Account getAccountByCustomerId(String customerId)
throws Exception;
}

步骤14: créer un nom appelé com.w3codebox.aspect du paquet。

步骤15: dans le paquet com.w3codebox.aspect dans la création d'une classe nommée AccountAspect de la classe.

Dans cette classe, nous avons réalisé l'annotation AfterThrowing en utilisant la méthode suivante @AfterThrowing。 Nous avons également défini afterThrowingAdvice()méthode.

Attention : Le nom défini dans l'attribut throwing (ex) doit correspondre au nom du paramètre dans la méthode advice. Sinon, l'avis ne sera pas exécuté.

AccountAspect.java

package com.w3codebox.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AccountAspect 
{
//implémentant l'avis après l'exception    
@AfterThrowing(value="execution("* com.w3codebox.service.impl.AccountServiceImpl.*(..))", throwing="ex")
public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex)
{
System.out.println("After throwing exception in method : ")+joinPoint.getSignature());
System.out.println("Exception est : ")+ex.getMessage());
}   
}

步骤16: 打开 AopAfterThrowingAdviceExampleApplication.java Ajoutez l'annotation au fichier @EnableAspectJAutoProxy.

Les annotations prennent en charge le traitement des aspects avec AspectJ @Aspect Composant de remarque. Il est utilisé conjointement avec l'annotation @Configuration.

nous avons utilisé l'annotation @EnableAspectJAutoProxy proxyTargetClass propriété. Propriété proxyTargetClass = true nous permet d'utiliser CGLIB (bibliothèque de génération de code) proxy, au lieu de la méthode d'proxy par interface JDK par défaut.

ConfigurableApplicationContext est une interface, qui fournit non seulement les méthodes client ApplicationContext d'Application Context, mais aussi des outils pour configurer l'application context.

AopAfterThrowingAdviceExampleApplication.java

package com.w3codebox;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.w3codebox.model.Account;
import com.w3codebox.service.impl.AccountService;
import com.w3codebox.service.impl.AccountServiceImpl;
@SpringBootApplication
//L'annotation @EnableAspectJAutoProxy permet de gérer les composants marqués avec @Aspect. Elle est similaire à la balise dans la configuration XML.
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AopAfterThrowingAdviceExampleApplication
{
    public static void main(String[] args)  
    {
        ConfigurableApplicationContext ac = SpringApplication.run(AopAfterThrowingAdviceExampleApplication.class, args);
        //从应用程序上下文获取account对象
        AccountService accountService = ac.getBean("accountServiceImpl", AccountServiceImpl.class);
        Account account;
        try 
        {
        //生成异常
        account = accountService.getAccountByCustomerId(null);
        if (account != null)
            System.out.println(account.getAccountNumber())+"\t"+account.getAccountType());
        } 
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

创建所有类和包后,项目目录如下所示:

步骤17: 打开 AopAfterThrowingAdviceExampleApplication.java 将其作为Java应用程序运行并打开文件。如下所示显示输出: