由于外部因素,有时我的咖啡豆无法正常初始化。比如MongoDB实例不在线。是否有一种优雅的方式来处理失败的bean初始化?以下是有问题的bean:
@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;
}
答案 0 :(得分:2)
如果您重新抛出异常,则上下文将停止加载,您的应用程序将无效。或者,如果您真的希望JVM完全停止调用System.exit(1)