How to gracefully handle bean initialization failures in a Spring 3 application?

Sometimes my beans may not initialize properly due to external factors. For example, a MongoDB instance is not connected to the network. Is there an elegant way to handle failed bean initializations? The following is a 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 screwed? } return null; } 
+4
source share
1 answer

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

+2
source

Source: https://habr.com/ru/post/1345101/


All Articles