Search code examples
javaplayframework-2.4

Playframework : Access named cache in Global Settings


I'm following the documentation here and trying to implement a named cache in my play (Java) project. I have a beforeStart method defined as below in my Global class:

public class Global extends GlobalSettings {
    @Inject
    @NamedCache("system-cache")
    CacheAPI cache;

    @Override
    public void beforeStart(Application app) {
    ...
    ...
    cache.set("test", "test"); //Throws a NullPointerException
}   

However, it seems like the dependency injection does not work for the Global object. I can access the default cache using:

import play.cache.Cache;
....
public class Global extends GlobalSettings {

    public void beforeStart(Application app) {
        Cache.set("test", "test"); //This works
    }
}

How do I access a named cache in the GlobalSettings class?


Solution

  • You need to use an eager singleton - this will allow you do inject whatever you want, and have it run as the app is starting up.

    From the documentation:

    GlobalSettings.beforeStart and GlobalSettings.onStart: Anything that needs to happen on start up should now be happening in the constructor of a dependency injected class. A class will perform its initialisation when the dependency injection framework loads it. If you need eager initialisation (for example, because you need to execute some code before the application is actually started), define an eager binding.

    Based on the documentation example, you would write a module that declares your singleton:

    import com.google.inject.AbstractModule;
    import com.google.inject.name.Names;
    
    public class HelloModule extends AbstractModule {
        protected void configure() {
    
            bind(MyStartupClass.class)
                    .toSelf()
                    .asEagerSingleton();
        }
    }
    

    In MyStartupClass, use the constructor to define your startup behaviour.

    public class MyStartupClass {
    
        @Inject
        public MyStartupClass(@NamedCache("system-cache") final CacheAPI cache) {    
            cache.set("test", "test");
        }
    }