Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Spring from Starting up after BeanInstantiationException (Tomcat)

for the project I'm currently working at there is the requirement to disable the webapp context to be started when spring fails to initialize some beans (that call webservices during initialization and therefore are likely to crash then).

However, when a bean throws any exception during initialization, it looks like this:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'latestAdsRepository' defined in file [...]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [...]: Constructor threw exception; nested exception is java.io.IOException: SHUT DOWN NOW!!
...
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [...]: Constructor threw exception; nested exception is java.io.IOException: SHUT DOWN NOW!!

however the context starts and all references to the bean that was not able to start are null. Needless to say, this causes various bad Nullpointer Exceptions all over the place. Especially because this bean is very important for the webapp.

So I need a way to explicitly tell Spring that this webapp has failed to start if a bean could not be initialized. System.exit(1) however is not an option, because there are also other webapps on this Tomcat server.

Any ideas?

like image 836
matt Avatar asked Nov 06 '22 09:11

matt


1 Answers

As far as I know, by default, the context startup fails when Spring fails to instantiate a bean, if the exception is propagated through the startup listener to the servlet container.

You can use the @Required annotation to mark a certain injection point as mandatory.

like image 117
Bozho Avatar answered Nov 09 '22 07:11

Bozho