1

現在、次のようなコントローラー内で UserService を接続するために Guice を使用しています。

@Singleton
class UserController @Inject()(userService: UserService) extends Controller {
  def show(userId: Int) {
      val user = userService.get(userId)
      Ok("hello " + user.name)
  }
}

私の UserService は次のようになります。

abstract class UserService {
  def get(userId: Int): User
}

class UserServiceImpl @Inject()(val userDao: UserDao) extends UserService {
  def get(userId: Int): User = {
    // ....
  }
}

依存関係として guice を削除して Cake パターンを使用したい場合、コードはどのようになり、これを Play に統合してコントローラーでこのサービスを使用できるようにするにはどうすればよいでしょうか?

4

1 に答える 1

0

これらすべてを整理する方法のアイデアを提供するために、パッケージ名を使用した提案を次に示します。

 package controllers.users

 trait UserController extends Controller {
     this: UserService =>

     def show(userId: Int) = {
         val user = this.get(userId)
         Ok("hello "  + user.name)
     }
 }

 package services.users

 trait UserService {
     def get(userId: Int): User
 }

 package services.users.impl

 trait UserServiceImpl extends UserService {
     def get(userId: Int) = { /*implementation*/ }
 }

 package controllers

 object UserController extends UserController with UserServiceImpl

サービスとコントローラーtraitは、プロジェクト内の好きな場所に配置できます。ルーティングを最も便利にするために、コントローラーをパッケージにobject直接配置する必要があります。controllers

于 2014-05-17T11:04:31.320 に答える