Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue to load webapp even if one spring bean initialization fails

Tags:

java

spring

So if spring initialization fails in a webapp then the webapp itself does not come up. To prevent this, I can probably not re-throw any exception from my code for that specific bean initialization and the webapp will continue to load, right?

Is there any other way to tell to spring not to fail the webapp itself on particular bean initialization failure?

like image 499
Prasanna Avatar asked Aug 03 '11 01:08

Prasanna


People also ask

Are beans in spring eagerly initialized by default yes or no?

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process.

How do you get all the beans in your spring boot application?

In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.

When Bean is initialized in spring?

By default, Spring ApplicationContext eagerly creates and initializes all 'singleton scoped' beans during application startup itself. ApplicationContext makes the bean available in BeanFactory.

Which method helps to initialize the bean?

Here, we will use init() method to execute all its code as the spring container starts up and the bean is instantiated, and destroy() method to execute all its code on closing the container.


2 Answers

Continue to load webapp even if one spring bean initialization fails

AFAIK, you can't do this.

I do multiple DNS lookups on start up. I do not want the webapp to fail if one of them fails.

In that case, you need to modify your bean(s) to handle the case where the DNS lookup fails, leaving the bean instance in a state where it is essentially inactive but harmless, or where it can retry the DNS lookup later on.

In short, you have to cope with this yourself.

like image 171
Stephen C Avatar answered Sep 21 '22 04:09

Stephen C


Have attribute lazy-init="true" in that bean and every dependant bean. Link for more details.

like image 44
Deniz Avatar answered Sep 18 '22 04:09

Deniz