1. 概述
在 Spring Boot 中,FailureAnalyzer 提供了一種方法,用於攔截應用程序啓動期間發生的異常,從而導致應用程序啓動失敗。
FailureAnalyzer 將異常的堆棧跟蹤替換為更易讀的消息,該消息由 FailureAnalysis 對象表示,該對象包含錯誤描述和建議的解決方案。
Boot 包含一系列用於常見啓動異常的分析器,例如 PortInUseException、NoUniqueBeanDefinitionException 和 UnsatisfiedDependencyException. 這些分析器位於 org.springframework.boot.diagnostics 包中。
在本快速教程中,我們將探討如何向現有分析器添加自定義的 FailureAnalyzer。
2. 創建自定義 FailureAnalyzer
要創建一個自定義 FailureAnalyzer,我們只需擴展抽象類 AbstractFailureAnalyzer – 它攔截指定異常類型並實現 analyze() API。
該框架提供了一個 BeanNotOfRequiredTypeFailureAnalyzer 實現,它僅處理注入的 Bean 是動態代理類時發生的 BeanNotOfRequiredTypeException 異常。
讓我們創建一個自定義 FailureAnalyzer,它可以處理所有類型為 BeanNotOfRequiredTypeException 的異常。 我們的類攔截該異常並創建一個包含有用的描述和操作消息的 FailureAnalysis 對象:
public class MyBeanNotOfRequiredTypeFailureAnalyzer
extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> {
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
BeanNotOfRequiredTypeException cause) {
return new FailureAnalysis(getDescription(cause), getAction(cause), cause);
}
private String getDescription(BeanNotOfRequiredTypeException ex) {
return String.format("The bean %s could not be injected as %s "
+ "because it is of type %s",
ex.getBeanName(),
ex.getRequiredType().getName(),
ex.getActualType().getName());
}
private String getAction(BeanNotOfRequiredTypeException ex) {
return String.format("Consider creating a bean with name %s of type %s",
ex.getBeanName(),
ex.getRequiredType().getName());
}
}3. 註冊自定義的 FailureAnalyzer
為了使自定義的 FailureAnalyzer 被 Spring Boot 識別,必須將其註冊到標準的 resources/META-INF/spring.factories 文件中,該文件包含 org.springframework.boot.diagnostics.FailureAnalyzer 鍵,並設置其值為我們類名的全限定名:
org.springframework.boot.diagnostics.FailureAnalyzer=\
com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer4. 自定義 FailureAnalyzer 在行動
讓我們創建一個簡單的示例,嘗試注入錯誤的類型的 Bean,以觀察我們的自定義 FailureAnalyzer 的行為。
讓我們創建兩個類:MyDAO 和 MySecondDAO,並對第二個類進行標註,將其定義為 Bean 類型的 myDAO。
public class MyDAO { }@Repository("myDAO")
public class MySecondDAO { }接下來,在 MyService 類中,我們將嘗試將 myDAO 豆注入到類型為 MyDAO 的變量中:
@Service
public class MyService {
@Resource(name = "myDAO")
private MyDAO myDAO;
}運行 Spring Boot 應用程序時,啓動將失敗,併產生以下控制枱輸出:
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean myDAO could not be injected as com.baeldung.failureanalyzer.MyDAO
because it is of type com.baeldung.failureanalyzer.MySecondDAO$$EnhancerBySpringCGLIB$$d902559e
Action:
Consider creating a bean with name myDAO of type com.baeldung.failureanalyzer.MyDAO結論
在本快速教程中,我們重點介紹瞭如何實現自定義的 Spring Boot <em FailureAnalyzer</em>。