简体   繁体   中英

How to 'gracefully' deal with bean initialization failures in Spring 3 application?

Sometimes my beans are not able to initialized properly due to external factors. Such as the MongoDB instance not being online. Is there a graceful way of handling the failed bean initializations? The following is the bean in question:

@Bean
public MorphiaDataSource morphiaDataSource() {
    try {
        MorphiaDataSource bean = new MorphiaDataSource();
        Mongo mongo = new Mongo(mongoHost, mongoPort);
        bean.setMongo(mongo);
        bean.setMorphia(new Morphia());
        bean.setDatabase(mongoDatabase);
        bean.setUsername(mongoUsername);
        bean.setPassword(mongoPassword);
        return bean;
    } catch(Exception e) {
        logger.error("Error creating MorphiaDataSource: " + e.getMessage());
        // Tell the context it's screwed?
    }
    return null;
}

If you rethrow the exception the context will stop loading and your application will be effectively dead. Or if you really want the JVM to completely stop call System.exit(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM