English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
After throwing è un tipo di consiglio in Spring AOP. Se il metodo lancia un'eccezione, assicura che il consiglio venga eseguito. Usiamo @AfterThrowing Usare l'annotazione per implementare il consiglio after-throwing.
Sintassi:
@AfterThrowing(PointCut="execution(expression) ", throwing="name")
Dove:
PointCut: Scegliere una funzione.
execution(expression):
throwing: Il nome dell'eccezione da restituire.
Realizziamo il consiglio after-throwing nell'applicazione.
Utilizzeremo l'esempio precedente in questa sezione. Puoi scaricare il progetto o apportare alcune modifiche all'esempio precedente.
Passaggio 1: Apri Spring Initializr http://start.spring.io 。
Passaggio 2: Fornisce GruppoNome. Forniamo il nome del gruppo com.w3codebox。
Passaggio 3: Fornisce Artifact Id.Fornisci l'Artifact Id aop-after-throwing-advice-example.
Passaggio 4: Aggiungi Spring Web Dipendenze.
Passaggio 5: Clicca GeneraPulsante. Quando clicchiamo sul pulsante "Genera", tutte le specifiche vengono impacchettate jar Dal file e scaricalo sul sistema locale.
Passaggio 6: Estrai
Passaggio 7: ImportaCartella, esegui i seguenti passaggi:
File->Importa->Progetto Maven esistente->Passo successivo->Esplora cartella aop-throwing-advice-example -> Completa.
Passaggio 8: Apri pom.xml File e aggiungi il seguente AOP Dipendenze. È utilizzata Spring AOP e AspectJ Introduzione alla programmazione ad aspect orientata.
<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>Progetto demo per 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>
Passo 9: Nel src/main/java cartella creare un nome com.w3codebox.model del pacchetto.
Passo 10: Nel pacchetto in com.w3codebox.model creare un nome Account di classe.
Nella classe "帐户", eseguire le seguenti operazioni:
definiscono due variabili di tipo String accountNumber e accountType . Fare clic con il tasto destro sul File -> Sorgente-> Usa campo per generare costruttore Genera Getters.
Fare clic con il tasto destro sul File -> Sorgente -> Genera Getters e Setters -> Seleziona Getters -> Genera Genera toString()
Fare clic con il tasto destro sul file -> Sorgente -> Genera 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 + "]"; } }
Passaggio 11: Crea un altro file chiamato com.w3codebox.service.impl del pacchetto.
Passaggio 12: In questo pacchetto, crea un file chiamato La classe AccountServiceImple.
In questa classe, definiamo il servizio di conto.
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 { //memorizzando dettagli del conto nel HashMap private static Map<String, Account> map = null; static { map = new HashMap<>(); //aggiungendo dettagli del conto nella mappa 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; } }
Passaggio 13: Nel pacchetto com.w3codebox.service.impl. Creare un nome di AccountService l'interfaccia.
AccountService.java
package com.w3codebox.service.impl; import com.w3codebox.model.Account; //creando un'interfaccia che lancia un'eccezione se l'ID del cliente non viene trovato public interface AccountService { public abstract Account getAccountByCustomerId(String customerId) throws Exception; }
Passaggio 14: Creare un nome di Pacchetto com.w3codebox.aspect.
Passaggio 15: Nel pacchetto com.w3codebox.aspect Creare un nome di AccountAspect di classe.
Nella classe, abbiamo implementato l'annotazione di consiglio dopo il lancio utilizzando il seguente metodo @AfterThrowing. Abbiamo anche definito afterThrowingAdvice()Metodo.
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 { //Implementazione dell'avviso dopo il lancio dell'eccezione @AfterThrowing(value="execution(* com.w3codebox.service.impl.AccountServiceImpl.*(..))", throwing="ex") public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) { System.out.println("Dopo l'eccezione lanciata nel metodo: "+joinPoint.getSignature()); System.out.println("L'eccezione è: "+ex.getMessage()); } }
Passaggio 16: Apri AopAfterThrowingAdviceExampleApplication.java Aggiungere l'annotazione al file @EnableAspectJAutoProxy.
Supporto delle annotazioni per la gestione con AspectJ @Aspect Componente di annotazione. Viene utilizzato insieme all'annotazione @Configuration.
abbiamo utilizzato l'annotazione @EnableAspectJAutoProxy proxyTargetClass proprietà. Proprietà proxyTargetClass = true ci permette di usare CGLIB (libreria di generazione del codice) proxy, invece del metodo di proxy JDK basato su interfaccia predefinito.
ConfigurableApplicationContext È un'interfaccia, oltre ai metodi client dell'ApplicationContext di Spring, fornisce strumenti per configurare l'ApplicationContext dell'applicazione.
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 annotazione supporta la gestione dei componenti etichettati con @Aspect. Assomiglia a un tag nell'configurazione xml. @EnableAspectJAutoProxy(proxyTargetClass=true) public class AopAfterThrowingAdviceExampleApplication { public static void main(String[] args) { ConfigurableApplicationContext ac = SpringApplication.run(AopAfterThrowingAdviceExampleApplication.class, args); //Recupero dell'oggetto account dall'ambiente dell'applicazione AccountService accountService = ac.getBean("accountServiceImpl", AccountServiceImpl.class); Account account; try { //Generazione dell'eccezione 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(); } } }
Dopo aver creato tutte le classi e i pacchetti, la struttura del progetto è la seguente:
Passaggio 17: Apri AopAfterThrowingAdviceExampleApplication.java Esegui il file come applicazione Java. Visualizza l'output come segue: