How to use play framework global object

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Filament.io 0 Flares ×

By defining a Global object in your project you can handle global settings for your application. You can use this global object to configure your applications start up parameters, configurations settings and probably initialize your application cache. Please note that the Global class should be defined in the root package.If you define it inside any package, the play framework will ignore it and it will never be executed during the play start.

To create a play framework global object, you need to define a class extending from play.GlobalSettings.

Here is an example

import play.*;

public class Global extends GlobalSettings {

}

You can override the onStart and onStop operations defined in GlobalSettings class to get notifications during application start and stop.

@Override
  public void onStart(Application app) {
    // code 
  }  
  
  @Override
  public void onStop(Application app) {
        // code 
  }  

You can use the Application object, passed as parameter to the above methods, to gather more details about the environment.Some of the useful methods are Applicaiton.isDev(), isProd() and isTest(). Knowing this will enable you to configure your application’s settings depending on the environment.

The Application object also exposes configuration’s via the Configuration object returned by the configuration() method. You can use this to access the settings dynamically.

Share this post:

Related Posts

  • pascal

    the Global object doesnt have to be in the root package, you can specify the class in application.conf : application.global=common.Global.

    Besides that I suggest to read, rather than the above (sorry Prem ;)) the Play doc, which is easy and well done for starters, and on this topic:

    http://www.playframework.com/documentation/2.1.x/JavaGlobal

    • http://pickadvice.com/ prem kumar

      Pascal, thanks for the information. I was not aware of that configuration.
      Of course I fully agree that it may be more useful for starters to read the play documentation.

  • Jhovani Cuadros

    What if I want to pass some object to the controllers ?