ServletContextListener-contextInitialized中的MongoDB连接类未加载

时间:2015-05-06 07:30:52

标签: java mongodb enums servletcontextlistener

我在一个web项目中使用Mongodb作为后端数据库,我正在尝试在contextInitialized()函数中连接MongoDB,但是tomcat服务器没有启动。但是当我打印一些值或做一些简单的事情而不是在该函数中加载一个类它工作正常。我无法跟踪发生的事情。代码

@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如下

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());
}

请帮帮我 谢谢 维基

1 个答案:

答案 0 :(得分:0)

你的代码中的问题是MongoDBClass没有初始化,因为你得到了db的名字,这个名字在tomcat服务器启动时没有设置``首先设置像@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 .
    }