开发者

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜