简体   繁体   中英

Play java framework Initializing variables on application startup in

I want to initialise some variables on application startup in Play framework. I'm following this document http://www.playframework.com/documentation/2.2.x/JavaGlobal for doing the same.. However when I run the application I get with the command "play run" the initialization does not happen. Am I doing something wrong here?

import com.Constants;

import controllers.Application;
import controllers.Utils;
import play.*;

public class Global extends GlobalSettings {
  public void onStart(Application app) throws Exception {
    Logger.info("Application has started");
    Constants.data1= Utils.getMerchantToBrMapping(Utils.getMerchantName());
    Constants.data2 = Utils.getBrToMerchantMapping(Utils.getMerchantName());
    Logger.info("Loaded the Merchant To BR Map");
  }
}

Your Application controller is being used as the implementation for the app parameter in your onStart(Applciation app) method.

In other words you are not overridding the onStart() callback method that Play will call, instead you are just defining your own custom method.

It should rather be like this:

import play.Application;
import play.GlobalSettings;
import play.Logger;

import controllers.Utils;
import com.Constants;

public class Global extends GlobalSettings {

    @Override
    public void onStart(Application app) {
        Logger.info("Application has started");
        Constants.data1 = Utils.getMerchantToBrMapping(Utils.getMerchantName());
        Constants.data2 = Utils.getBrToMerchantMapping(Utils.getMerchantName());
        Logger.info("Loaded the Merchant To BR Map");
    }
}

note the import of import play.Application; and not your controller. Also note that onStart() does not throw an Exception. If you had added the @Override annotation it would have hinted at the problem, so keep in mind for future reference.

More on Global here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM