views:

80

answers:

2

Hello, 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?

+2  A: 

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.

Bozho
Thanks for your answer, however using the @Required annotation does not help at all. What I noticed is: When the context starts up (after not being able to create all beans) it will try to re-create the missing beans each time, they are used. Is this some new kind of default behaviour? I haven't enabled anything like that in config.
matt
what scope are your beans?
Bozho
They are of Default (Singleton) scope
matt
perhaps you can give applicationContext.xml..because I'm almost sure the default behaviour is to not initialize the context. Also, provide more of tomcat logs, mainly the SEVERE parts.
Bozho
A: 

How are you loading the Spring context?

Sounds like you might be doing it manually (i.e. you are calling new ApplicationContext() somewhere), instead you should use the ContextLoaderListener so that your context is loaded automatically upon application startup (and shutdown during application shutdown). Exceptions during the Spring context startup will propogate to failing the web application context startup.

matt b