SpringBootを使用してカスタムFailureAnalyzerを作成する
1. 概要
SpringBootのFailureAnalyzerは、アプリケーションの起動中に発生してアプリケーションの起動に失敗する例外をインターセプトする方法を提供します。
FailureAnalyzer は、例外のスタックトレースを、エラーの説明と推奨されるアクションを含むFailureAnalysisオブジェクトで表されるより読みやすいメッセージに置き換えます。
Bootには、次のような一般的な起動例外用の一連のアナライザーが含まれています。 PortInUseException 、 NoUniqueBeanDefinitionException 、 と
このクイックチュートリアルでは、独自のカスタムFailureAnalyzerを既存のものに追加する方法を見ていきます。
2. カスタムFailureAnalyzerの作成
カスタムFailureAnalyzerを作成するには、抽象クラス AbstractFailureAnalyzer を拡張するだけです。これは、指定された例外タイプをインターセプトし、 analysis()APIを実装します。
フレームワークは、注入されるBeanが動的プロキシクラスである場合にのみ、例外BeanNotOfRequiredTypeExceptionを処理するBeanNotOfRequiredTypeFailureAnalyzer実装を提供します。
カスタムを作成しましょう FailureAnalyzer タイプのすべての例外を処理します
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がSpringBootによって考慮されるためには、orgを含む標準のresources / META-INF /spring.factoriesファイルに登録する必要があります。私たちのクラスのフルネームの値を持つspringframework.boot.diagnostics.FailureAnalyzerキー:
org.springframework.boot.diagnostics.FailureAnalyzer=\
com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer
4. カスタムFailureAnalyzerの動作
間違ったタイプのbeanを挿入して、カスタムFailureAnalyzerがどのように動作するかを確認する非常に簡単な例を作成してみましょう。
2つのクラスMyDAOとMySecondDAOを作成し、2番目のクラスにmyDAOというbeanとして注釈を付けましょう。
public class MyDAO { }
@Repository("myDAO")
public class MySecondDAO { }
次に、 MyService クラスで、タイプMySecondDAOのmyDAObeanをタイプ
@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
5. 結論
このクイックチュートリアルでは、カスタムSpring Boot FailureAnalyzerの実装方法に焦点を当てました。
いつものように、例の完全なソースコードは、GitHubのにあります。