I am using Mongodb as Back-End database in a web project and i am trying to connect the MongoDB in contextInitialized() function but the tomcat server is not starting.But when i print some values or do some simple things rather than load a class in that function it works fine.I can't track what is happening.The code
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
MongoDBClass.INSTANCE.getSomeDB().getCollection("UserDB");
System.out.println("Context Created");//This is working
context = contextEvent.getServletContext();
context.getServerInfo();
MongoDBClass.INSTANCE.getSomeDB().getCollection("UserDB");//Server loading and unable to start .
}
MongoDBClass is as follows
public enum MongoDBClass {
INSTANCE;
private static final String MONGO_DB_HOST = "hostURL";
private Mongo mongoObject;
private DB someDB;
String DB_NAME = null;
MongoClientOptions options = null;
MongoDBClass() {
options = MongoClientOptions.builder().connectionsPerHost(100)
.readPreference(ReadPreference.secondaryPreferred()).build();
mongoObject = new MongoClient(new ServerAddress(MONGO_DB_HOST,27001),options);
someDB = mongoObject.getDB(Nutans_Mongo.getNameOFDB());
}
please help me out Thanks Vicky
The problem in your code is MongoDBClass is not intialized because you are getting name of db which is not set during start the start of tomcat server `` set that first like @Override
public void contextInitialized(ServletContextEvent contextEvent) {
Nutans_Mongo.setNameOFDB("someDBNAME"); //then intialize MongoDBCLass
MongoDBClass.INSTANCE.getSomeDB().getCollection("UserDB");
System.out.println("Context Created");//This is working
context = contextEvent.getServletContext();
context.getServerInfo();
MongoDBClass.INSTANCE.getSomeDB().getCollection("UserDB");//Server loading and unable to start .
}