Spring - catch bean creation exception

configuration, exception, java, spring

Solution

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);
    }
  }
}

Problem

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(); } } } ``` Is that possible to define exception handlers for bean instantiation using Spring using XML-based or annotation-based configuration?

Original source