After throwing是Spring AOP中的建議類型。如果方法拋出異常,它將確保建議運行。我們使用 @AfterThrowing 注解來實現(xiàn)擲后建議。
語法:
@AfterThrowing(PointCut="execution(expression) ", throwing="name")
其中:
PointCut: 選擇一個函數(shù)。
execution(expression):
throwing: 要返回的異常的名稱。
讓我們在應(yīng)用程序中實現(xiàn)after-throwing建議。
我們將在本節(jié)中使用前面的示例。您可以下載項目或在上一個示例中進(jìn)行一些修改。
步驟1: 打開Spring Initializr http://start.spring.io 。
第2步: 提供 組名稱。我們提供了組名 com.nhooo。
步驟3: 提供了 Artifact Id。提供Artifact Id aop-after-throwing-advice-example.。
步驟4: 添加 Spring Web 依賴項。
步驟5: 點擊 生成按鈕。當(dāng)我們單擊"生成"按鈕時,它將所有規(guī)范包裝在 jar 文件中,并將其下載到本地系統(tǒng)。
步驟6: 提取
第7步: 導(dǎo)入文件夾,請執(zhí)行以下步驟:
File->Import- >現(xiàn)有Maven項目->下一步->瀏覽文件夾 aop-throwing-advice-example -> Finish。
步驟8: 打開 pom.xml 文件,并添加以下 AOP 依賴項。它是使用 Spring AOP 和 AspectJ 進(jìn)行面向方面編程的入門。
<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.nhooo</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: 在 src/main/java 文件夾 中創(chuàng)建名稱為 com.nhooo.model 的包。
步驟10: 在包 com.nhooo.model中創(chuàng)建一個名稱為 Account 的類。
在"帳戶"類中,執(zhí)行以下操作:
定義了兩個類型為String的變量 accountNumber 和 accountType 。 右鍵單擊File -> Source->使用字段生成構(gòu)造函數(shù) 生成Getters。
右鍵單擊File-> Source-> Generate Getters和Setters->選擇Getters-> Generate 生成 toString()
右鍵單擊文件->源->生成toString()
Account.java
package com.nhooo.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: 創(chuàng)建另一個名為 com.nhooo.service.impl的包。
步驟12: 在此程序包中,創(chuàng)建一個名稱為 AccountServiceImple的類。
在該類中,我們定義了帳戶服務(wù)。
AccountServiceImpl.Java
package com.nhooo.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.nhooo.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: 在包 com.nhooo.service.impl。 中創(chuàng)建一個名稱為 AccountService 的接口。
AccountService.java
package com.nhooo.service.impl;
import com.nhooo.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: 創(chuàng)建名稱為 com.nhooo.aspect的包。
步驟15: 在包 com.nhooo.aspect 中創(chuàng)建一個名稱為 AccountAspect 的類。
在該類中,我們通過使用以下方式實現(xiàn)了投擲后建議注解 @AfterThrowing。 我們還定義了 afterThrowingAdvice()方法。
AccountAspect.java
package com.nhooo.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.nhooo.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 is:"+ex.getMessage());
}
}
步驟16: 打開 AopAfterThrowingAdviceExampleApplication.java 文件并添加注解 @EnableAspectJAutoProxy。
注解支持處理帶有AspectJ的 @Aspect 批注的組件。它與@Configuration批注一起使用。
我們使用了@EnableAspectJAutoProxy批注的 proxyTargetClass 屬性。屬性 proxyTargetClass = true 允許我們使用 CGLIB (代碼生成庫)代理,而不是默認(rèn)的基于接口的JDK代理方法。
ConfigurableApplicationContext 是一個接口,除了ApplicationContext中的應(yīng)用程序上下文客戶端方法外,還提供了用于配置應(yīng)用程序上下文的工具。
AopAfterThrowingAdviceExampleApplication.java
package com.nhooo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.nhooo.model.Account;
import com.nhooo.service.impl.AccountService;
import com.nhooo.service.impl.AccountServiceImpl;
@SpringBootApplication
//@EnableAspectJAutoProxy注解支持處理用@Aspect注解標(biāo)記的組件。它類似于xml配置中的標(biāo)記。
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AopAfterThrowingAdviceExampleApplication
{
public static void main(String[] args)
{
ConfigurableApplicationContext ac = SpringApplication.run(AopAfterThrowingAdviceExampleApplication.class, args);
//從應(yīng)用程序上下文獲取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();
}
}
}
創(chuàng)建所有類和包后,項目目錄如下所示:
步驟17: 打開 AopAfterThrowingAdviceExampleApplication.java 文件并將其作為Java應(yīng)用程序運行。它顯示輸出,如下所示: