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?
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);
}
}
}
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With