使用 @controlleradvice 结合 @exceptionhandler 可以捕获 bean 初始化异常,但前提是这些异常发生在请求处理阶段。对于应用启动时的初始化异常,必须通过自定义 errorcontroller 或注册 applicationlistener 来处理。

如何捕获启动时的 Bean 初始化异常
在 Spring Boot 启动过程中,如果某个 Bean 的初始化失败(例如构造函数抛出异常),默认行为是程序直接终止并打印堆栈信息。要捕获这类异常,需要实现 ApplicationListener<applicationfailedevent></applicationfailedevent> 接口,监听启动失败事件。

import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class StartupFailureHandler implements ApplicationListener<ApplicationFailedEvent> {
@Override
public void onApplicationEvent(ApplicationFailedEvent event) {
Throwable cause = event.getException();
System.out.println("Startup failed: " + cause.getMessage());
// 这里可以记录日志或发送通知
}
}如何处理请求阶段的 Bean 创建异常
当 Bean 的初始化发生在请求处理期间(例如懒加载或作用域为 prototype 的 Bean),可以使用全局异常处理器来捕获。通过定义一个带有 @ControllerAdvice 注解的类,并在其中添加 @ExceptionHandler 方法来处理 BeanCreationException。

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BeanCreationException.class)
public String handleBeanCreationException(BeanCreationException ex) {
return "Bean creation failed: " + ex.getRootCause().getMessage();
}
}Bean 初始化失败时如何获取具体原因
在 ApplicationFailedEvent 中,可以通过 getException() 方法获取根异常。如果根异常是 BeanCreationException,则可以进一步检查其 getRootCause() 来获取具体的错误原因。这样可以更精确地定位问题所在。


















