本文介绍了Spring-捕获bean创建异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的代码中捕获bean实例化异常.我有什么选择?一种方法是使用基于Java的容器配置:

I want to catch bean instantiation exceptions in my code. What options do I have?One way to do this is to use Java-based container configuration:

@Configuration
public class AppConfig {
  @Bean
  public SomeBean someBean() {
    try {
      return new SomeBean(); // throws SomeException
    } catch(SomeException se) {
      return new SomeBeanStub();
    }
  }
}

是否可以使用Spring基于XML或基于注释的配置来定义用于bean实例化的异常处理程序?

Is that possible to define exception handlers for bean instantiation using Spring using XML-based or annotation-based configuration?

推荐答案

方法 someBean 应该捕获 SomeException ,然后抛出 BeanCreationException SomeException 作为原因:

Method someBean should catch SomeException and then throw BeanCreationException with SomeException as the cause:

@Configuration
public class AppConfig {
  @Bean
  public SomeBean someBean() {
    try {
      return new SomeBean(); // throws SomeException
    } catch (SomeException se) {
      throw new BeanCreationException("someBean", "Failed to create a SomeBean", se);
    }
  }
}

这篇关于Spring-捕获bean创建异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:38