2017-07-24 511 views
-1

這是我的代碼:播放框架依賴注入錯誤

package controllers 

import javax.inject.Inject 

import scala.concurrent.Future 

import play.api.Logger 
import play.api.mvc.{ Action, Controller } 
import play.api.libs.concurrent.Execution.Implicits.defaultContext 
import play.api.libs.functional.syntax._ 
import play.api.libs.json._ 

// Reactive Mongo imports 
import reactivemongo.api.Cursor 
import reactivemongo.api.ReadPreference 

import play.modules.reactivemongo.{ // ReactiveMongo Play2 plugin 
MongoController, 
ReactiveMongoApi, 
ReactiveMongoComponents 

} 

// BSON-JSON conversions/collection 
import reactivemongo.play.json._ 
import play.modules.reactivemongo.json.collection._ 

/* 
* Example using ReactiveMongo + Play JSON library. 
* 
* There are two approaches demonstrated in this controller: 
* - using JsObjects directly 
* - using case classes that can be turned into JSON using Reads and Writes. 
* 
* This controller uses JsObjects directly. 
* 
* Instead of using the default Collection implementation (which interacts with 
* BSON structures + BSONReader/BSONWriter), we use a specialized 
* implementation that works with JsObject + Reads/Writes. 
* 
* Of course, you can still use the default Collection implementation 
* (BSONCollection.) See ReactiveMongo examples to learn how to use it. 
*/ 
class Application @Inject() (val reactiveMongoApi: ReactiveMongoApi) 
    extends Controller with MongoController with ReactiveMongoComponents { 

    def collection: Future[JSONCollection] = 
    database.map(_.collection[JSONCollection]("Persons")) 

    def index = Action { Ok("works") } 

    def create(name: String, age: Int) = Action.async { 
    val json = Json.obj(
     "name" -> name, 
     "age" -> age, 
     "created" -> new java.util.Date().getTime()) 

    collection.flatMap(_.insert(json)).map(lastError => 
     Ok("Mongo LastError: %s".format(lastError))) 
    } 
    } 

從來就一個錯誤,說不容查找數據庫值(數據庫ReactiveMongoApi特質的成員),所以我想有什麼問題依賴注入。我還添加了這條線到build sbt:

添加routesRiantes:= InjectedRoutesGenerator 任何想法?謝謝!

回答

1

您需要參考注入的API。即,用reactiveMongoApi.database代替database

class Application @Inject() (val reactiveMongoApi: ReactiveMongoApi) 
    extends Controller with MongoController with ReactiveMongoComponents { 

    def collection: Future[JSONCollection] = 
    reactiveMongoApi.database.map(_.collection[JSONCollection]("Persons")) 
    ... 
}