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

SpringBoot AOP @AfterThrowing

After throwing是Spring AOP中的建议类型。如果方法抛出异常,它将确保建议运行。我们使用 @AfterThrowing 注解来实现掷后建议。

语法:

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

其中:

PointCut: 选择一个函数。

execution(expression):

throwing: 要返回的异常的名称。

让我们在应用程序中实现after-throwing建议。

Spring Boot @AfterThrowing示例

我们将在本节中使用前面的示例。您可以下载项目或在上一个示例中进行一些修改。

Schritte1: 打开Spring Initializr http://start.spring.io 。

第2步骤: 提供 名称。我们提供了组名 com.w3codebox。

Schritte3: 提供了 Artifact Id。提供Artifact Id aop-after-throwing-advice-example.。

Schritte4: 添加 Spring Web 依赖项。

Schritte5: 点击 Erstellen Sie按钮。当我们单击"生成"按钮时,它将所有规范包装在 jar 文件中,并将其下载到本地系统。

Schritte6: 提取

第7步骤: 导入文件夹,请执行以下步骤:

Datei-> 导入- > 现有Maven项目-> 下一步-> 浏览文件夹 aop-throwing-advice-example -> 完成。

Schritte8: Öffnen pom.xml 文件,并添加以下 AOP 依赖项。它是使用 Spring AOP und 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>

Schritte9: im src/main/java Verzeichnis Erstellen Sie einen Namens com.w3codebox.model Paket.

Schritte10: im Paket com.w3Erstellen Sie in codebox.model einen Namens Account der Klasse.

Führen Sie in der "Konto"-Klasse die folgenden Aktionen aus:

definierten zwei Variablen vom Typ String accountNumber und accountType . Klicken Sie mit der rechten Maustaste auf Datei -> Quelle-> Erstellen Sie den Konstruktor mit den Feldern Generieren Sie Getter.
Klicken Sie mit der rechten Maustaste auf Datei-> Quelle-> Generieren Sie Getter und Setter-> Wählen Sie Getter-> Generieren
Erstellen Sie toString()
Klicken Sie mit der rechten Maustaste auf die Datei-> Quelle-> Erstellen Sie 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 + "]";
}
}

Schritte11: Erstellen Sie einen weiteren Namens com.w3codebox.service.impl des Pakets erstellt.

Schritte12: In diesem Paket wird ein Namens Die Klasse AccountServiceImple.

In dieser Klasse definieren wir die Kontoservice.

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 
{
//Speichern Sie die Kontodetails im HashMap
private static Map<String, Account> map = null;
static
{
map = new HashMap<>();
//Fügen Sie die Kontodetails im Map hinzu
map.put("M",4546779, new Account("10441117000", "Saving Account"));
map.put("K",2434567, 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;
}
}

Schritte13: im Paket com.w3codebox.service.impl. in der Erstellung eines Namens AccountService Das Interface.

AccountService.java

package com.w3codebox.service.impl;
import com.w3codebox.model.Account;
//erstellen eines Interfaces, das eine Ausnahme wirft, wenn die Kunden-ID nicht gefunden wird 
public interface AccountService 
{
public abstract Account getAccountByCustomerId(String customerId)
throws Exception;
}

Schritte14: Erstellen eines Namens com.w3Paket codebox.aspect.

Schritte15: im Paket com.w3codebox.aspect in der Erstellung eines Namens AccountAspect der Klasse.

In dieser Klasse haben wir den AfterThrowing-Annotation durch die Verwendung der folgenden Art implementiert @AfterThrowing。 Wir haben auch definiert afterThrowingAdvice()Methode.

Beachten Sie: Der Name, den wir in der Property throwing definieren (ex), muss mit dem Namen des Parameters in der advice-Methode übereinstimmen. Andernfalls wird empfohlen, dass dies nicht ausgeführt wird.

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 
{
//implementing after throwing advice    
@AfterThrowing(value="execution("* com.w3codebox.service.impl.AccountServiceImpl.*(..)", throwing="ex")
public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex)
{
System.out.println("Nach dem Auswerfen einer Ausnahme im Methoden:")+joinPoint.getSignature());
System.out.println("Exception ist:")+ex.getMessage());
}   
}

Schritte16: Öffnen AopAfterThrowingAdviceExampleApplication.java Datei und fügen Sie Anmerkungen hinzu @EnableAspectJAutoProxy.

Annotationen unterstützen die Verarbeitung von AspectJ-basierten @Aspect Komponenten mit Anmerkungen. Es wird zusammen mit @Configuration-Anmerkungen verwendet.

Wir verwenden den @EnableAspectJAutoProxy-Annotation. proxyTargetClass Eigenschaft. Eigenschaft proxyTargetClass = true ermöglicht es uns, CGLIB (Codegenerierungsbibliothek) Proxy anstatt der Standard-JDK-Proxy-Methode, die auf Basis von Interfaces basiert.

ConfigurableApplicationContext ist eine Schnittstelle, die neben den ApplicationContext-Anwendungscontext-Clientmethoden auch Werkzeuge zur Konfiguration des Anwendungscontexts bereitstellt.

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
//@EnableAspectJAutoProxy Annotierung unterstützt die Verarbeitung von Komponenten, die mit @Aspect markiert sind. Es ähnelt der Marke in der xml-Konfiguration.
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AopAfterThrowingAdviceExampleApplication
{
    public static void main(String[] args)  
    {
        ConfigurableApplicationContext ac = SpringApplication.run(AopAfterThrowingAdviceExampleApplication.class, args);
        //Account-Objekt aus der Anwendungskontext holen
        AccountService accountService = ac.getBean("accountServiceImpl", AccountServiceImpl.class);
        Account account;
        try 
        {
        //Erzeugen eines Ausnahme
        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();
        }
    }
}

Nachdem alle Klassen und Pakete erstellt wurden, sieht der Projektverzeichnis wie folgt aus:

Schritte17: Öffnen AopAfterThrowingAdviceExampleApplication.java Datei und als Java-Anwendung ausführen. Es zeigt die Ausgabe wie folgt: