簡體   English   中英

Spring-Boot:嘗試從@PostConstruct 方法拋出自定義 RunTimeException 失敗

[英]Spring-Boot: Trying to throw a custom RunTimeException from @PostConstruct method fails

基本上,我的代碼在下面。 考慮到這是代碼的“測試”狀態。 最初的問題是調用 init() 到另一個拋出已檢查異常的類。 此拋出被 try/catch 塊捕獲,然后應用程序在嘗試創建異常時失敗。 為了清楚起見,所有這些都已刪除,因為問題出在“MyCustomRuntimeException”創建中。

@Component
public class ClassName {

  public ClassName() {
    //minor, non problematic operations.
  }

  @PostConstruct
  public void init() {
    throw new MyCustomRuntimeException("AAAAAAAH");
  }

}

MyCustomRuntimeException 定義如下:

public class MyCustomRuntimeException extends RuntimeException {

  public MyCustomRuntimeException (String message) {
    super(message);
  }
}

而且,在創建使用此類的類時,我收到了“UnsatisfiedDependencyException”。 控制台指向拋出新的 MyCustomRuntimeException 的那一行,我真的不明白發生了什么。

此外,“MyCustomRuntimeException”開始作為一個常規異常,但我看到我應該拋出一個 RunTimeException 因為@PostConstruct 禁止拋出已檢查的異常 而且我還嘗試在沒有運氣的情況下拋出標准的 RunTimeException。

所以,我在這里一無所知。 關於為什么我不能拋出這個異常的任何想法?

上下文中的每個 bean 都需要正確創建。 當發生錯誤時,bean 的創建將停止/失敗並且上下文(或換句話說您的應用程序)將不會啟動。

您會收到UnsatisfiedDependencyException因為ClassName bean 是因為另一個 bean 需要它而創建的。 在構造ClassName ,它將調用ClassName bean 的@PostConstruct ,並且由於異常而失敗。 因此不會創建實例,因此會出現UnsatisfiedDependencyException

UnsatisfiedDependencyException的根本原因將是您自己的初始化方法拋出的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM