charbelfa charbelfa - 3 months ago 11
Java Question

Instantiating variables in Controller on start of application using Play Framework

I am using Java through the Play Framework to implement an API. I am trying to instantiate a few variables on the start of the application that should last for the entire life of the application and that are to be used in my HomeController.
These variables are objects that can be used to call functions from a specific class.

I have read that the best way to implement code that executes on the start of the application is to use Dependency Injection but I did not understand how to do it.

Can you please clarify how this is done?

Thank you.

Answer

You can find here and here more examples of dependency injection in Play.

After you got the idea, it should be easy to implement. To define an object, that should last for the application entire lifecycle:

  1. Define the class (of such object) with @Singleton annotation:

    @Singleton  
    public class MyClass4AppLifecycle {  
        public MyClass4AppLifecycle() {  
           ...
        }
        .... 
    }
    
  2. Add to the controller a data member with @Inject annotation:

    public class MyController extends Controller {
        @Inject
        private MyClass4AppLifecycle myGlobalObject;
        ...   
    

    Note: since you mentioned several objects, member inject annotation seems more appropriate, that a constructor annotation.

  3. Register you class for dependency injection in the default module (it is the simplest way):

    public class Module extends AbstractModule {  
        @Override  
        protected void configure() {  
            bind(MyClass4AppLifecycle.class).asEagerSingleton();
        }  
    } 
    
  4. Repeat the three above for each type you need to have globally