我有一个带有构造函数的Controller,在其中注入缓存,但是我想在创建实例时在构造函数中调用一个方法。我知道我们可以使用创建一些辅助构造函数
def this(foo:Foo){}
但是在我的情况下,因为是播放框架,所以实例化我的引导程序要复杂一些。
这是我的代码
class SteamController @Inject()(cache: CacheApi) extends BaseController {
private val GAME_IDS_LIST_API: String = "api.steampowered.com/ISteamApps/GetAppList/v2"
private val GAME_API: String = "store.steampowered.com/api/appdetails?appids="
private val GAME_KEY: String = "games"
def games = Action { implicit request =>
var fromRequest = request.getQueryString("from")
if (fromRequest.isEmpty) {
fromRequest = Option("0")
}
val from = Integer.parseInt(fromRequest.get) * 10
val to = from + 10
loadGameIds()
Ok(html.games(SteamStore.gamesIds(cache.getVal[JSONArray](GAME_KEY), from, to), cache.jsonArraySize(GAME_KEY)/10))
}
private def loadGameIds(): Unit = {
val games = cache.get(GAME_KEY)
if (games.isEmpty) {
get(s"$GAME_IDS_LIST_API", asJsonGamesId)
cache.set(GAME_KEY, lastResponse.get, 60.minutes)
}
}
我想要的是在实例化类时将调用并缓存loadGameIds。
有什么建议吗?
问候。
如果我正确理解了您的问题,您只是想向构造函数主体添加一些语句?如果是这样,您可以在类本身的主体中简单地做到这一点。在您的情况下,将如下所示:
class SteamController @Inject()(cache: CacheApi) extends BaseController {
...
private val GAME_KEY: String = "games"
loadGameIds() // <-- Here we are calling from the main constructor body
def games = Action { implicit request =>
...
}
...
}
这样做时,通常最好在类中所有val和var声明之后执行其他代码,以确保在运行其他构造函数代码时已正确初始化它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句