Search code examples
javaspringdependency-injectionjava-6java-5

Can I ignore BeanCreationException and inject null instead?


We have a situation where our Spring wires up some beans that include ActiveMQ classes built with Java 6. Our application runs on customer's servers, so we can't guarantee that they have Java 6 or later installed. If they happen to have Java 5, the application can't start because of BeanCreationExceptions with the classes that depend on ActiveMQ (root cause being a UnsupportedClassVersionError).

So my question is, is there any way to ignore a BeanCreationException and still start the application? I want to be able to display an error message saying that they need to install Java 6 or later, but since the application can't even start, I never have a chance to do this.

My hunch is that there is no way to do this, because Spring needs to be able to guarantee that my application is built properly after initialization, but I thought I would ask anyway. Any other suggestions for how to accomplish my end goal would also be helpful and appreciated.

We are using Spring 3.0.6

Thanks!


Solution

  • First off, any throwables that are a subclass of java.lang.Error are generally considered to be non-recoverable. So while it's possible to catch them, it's strongly discouraged:

    An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

    However, if all you're going to do is display an error message, then you should be able to get away with it.

    SO to get back to your question, I suggest creating an implementation of Spring's FactoryBean interface, which would try to load the ActiveMQ classes. If it works, then it can return the appropriate object from FactoryBean.getObject. If it fails (via a caught UnsupportedClassVersionError), then it can return either a null, or some other object representing that condition.