java - Playframework : Access named cache in Global Settings -
i'm following documentation here , trying implement named cache in play (java) project. have beforestart method defined below in global class:
public class global extends globalsettings { @inject @namedcache("system-cache") cacheapi cache; @override public void beforestart(application app) { ... ... cache.set("test", "test"); //throws nullpointerexception }
however, seems dependency injection not work global object. can access default cache using:
import play.cache.cache; .... public class global extends globalsettings { public void beforestart(application app) { cache.set("test", "test"); //this works } }
how access named cache in globalsettings class?
you need use eager singleton - allow inject whatever want, , have run app starting up.
from documentation:
globalsettings.beforestart , globalsettings.onstart: needs happen on start should happening in constructor of dependency injected class. class perform initialisation when dependency injection framework loads it. if need eager initialisation (for example, because need execute code before application started), define eager binding.
based on documentation example, write module declares 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 constructor define startup behaviour.
public class mystartupclass { @inject public mystartupclass(@namedcache("system-cache") final cacheapi cache) { cache.set("test", "test"); } }
Comments
Post a Comment