Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - catch bean creation exception

Tags:

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?

like image 518
khachik Avatar asked Nov 22 '12 08:11

khachik


2 Answers

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);
    }
  }
}
like image 132
Derek Mahar Avatar answered Sep 18 '22 12:09

Derek Mahar


Just for completeness.

You can also lazy init the bean and catch the exception the first time you use the bean.

spring config:

<bean id="a" class="A" lazy-init="true" />

In java:

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

public class B {

    @Autowired
    @Lazy
    A a;

    public void foo(){
         try{
               a.foo();
         } catch (BeanCreationException e){
               // ignore if you want
         }
    }
}
like image 31
mjspier Avatar answered Sep 18 '22 12:09

mjspier