Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 274
Sean Adkinson Avatar asked Jan 17 '12 22:01

Sean Adkinson


1 Answers

If you can upgrade to Spring 3.1 (stable), take advantage of Java configuration:

@Bean
public SomeBean public someBean() {
    if(isEverythingOkWithJavaVersion()) {
        return new CorrectBean();
    } else {
        return null;
    }
}

or:

@Bean
public SomeBean public someBean() {
    try {
        return new CorrectBean();
    } catch(UnsupportedClassVersionError e) {
        log.warn("", e);
        return null;
    }
}

In older versions of Spring FactoryBean might be used to implement the same logic. Instead of returning null you might also return some fake implementation that you can discover later and warn the user when the application tries to use it.

like image 86
Tomasz Nurkiewicz Avatar answered Sep 29 '22 23:09

Tomasz Nurkiewicz