当前位置: 首页>>代码示例>>Scala>>正文


Scala Injector类代码示例

本文整理汇总了Scala中play.api.inject.Injector的典型用法代码示例。如果您正苦于以下问题:Scala Injector类的具体用法?Scala Injector怎么用?Scala Injector使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Injector类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: AppLoader

//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource

import controllers.UsersController
import io.getquill._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.evolutions.Evolutions
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.api.routing.sird._
import models.{Users}

class AppLoader extends ApplicationLoader {
  override def load(context: Context): Application = new BuiltInComponentsFromContext(context) with DBComponents with HikariCPComponents {

    lazy val db = new H2JdbcContext[SnakeCase](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])


    lazy val users = new Users(db)
    lazy val usersController = new UsersController(users)

    val router = Router.from {
      case GET(p"/users/${long(id)}")    => usersController.get(id)
      case POST(p"/users")               => usersController.create
      case DELETE(p"/users/${long(id)}") => usersController.delete(id)
      case PUT(p"/users/${long(id)}")    => usersController.update(id)
    }

    override lazy val injector: Injector =
      new SimpleInjector(NewInstanceInjector) + users + router + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + global

    Evolutions.applyEvolutions(dbApi.database("default"))

  }.application
} 
开发者ID:getquill,项目名称:play-quill-jdbc,代码行数:38,代码来源:AppLoader.scala

示例2: AppLoader

//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource

import controllers.MainController
import io.getquill._
import models.Services
import unus.db._
import unus.helpers.Conf
import unus.model.FeatureBuilder
import unus.stage.{BlockerCacher, DatabaseBackup, PatientCacher, PatientDatabase}
import org.flywaydb.play.FlywayPlayComponents
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.filters.csrf._
import router.Routes

class AppLoader extends ApplicationLoader {
  override def load(context: Context): Application = new BuiltInComponentsFromContext(context)
    with DBComponents with HikariCPComponents  with CSRFComponents
    with FlywayPlayComponents with play.filters.HttpFiltersComponents with _root_.controllers.AssetsComponents {

    lazy val db = new PostgresJdbcContext[PostgresEscape](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])

    lazy val services = new Services(db)
    lazy val patientCacher = new PatientCacher
    lazy val repo = new Repository(db)
    lazy val blockerCachers = Conf.blockers.map(new BlockerCacher(repo, patientCacher.value, _))
    lazy val features =  Conf.features
    lazy val controller = new MainController(services, repo, patientCacher, blockerCachers, features)(controllerComponents)

    lazy val router: Router = new Routes(httpErrorHandler, controller)

    

    override lazy val injector: Injector =
      new SimpleInjector(NewInstanceInjector) + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + router

    override lazy val httpFilters = Seq(csrfFilter)

    flywayPlayInitializer

    new PatientDatabase(repo, patientCacher).run()

    if(services.getLabelCount == 0) {
      new DatabaseBackup[Label]("Label").load()
    }

    if(services.getBlockedRowCount == 0) {
      new DatabaseBackup[BlockedRow]("BlockedRow").load()
    }

  }.application
} 
开发者ID:mindfulmachines,项目名称:unus,代码行数:57,代码来源:AppLoader.scala

示例3: ApplicationLoader

//设置package包名称以及导入依赖的类
package init

import play.api.ApplicationLoader.Context
import play.api.{BuiltInComponentsFromContext, LoggerConfigurator}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.routing.Router

import clients._
import controllers._
import router.Routes

class ApplicationLoader extends play.api.ApplicationLoader {

  def load(context: Context) = {
    new ApplicationComponents(context)
      with DefaultClientComponents
  }.application

}

class ApplicationComponents(context: Context)
  extends BuiltInComponentsFromContext(context)
  with AhcWSComponents
{

  self: ClientComponents =>

  LoggerConfigurator(context.environment.classLoader).foreach { loggerConfigurator =>
    loggerConfigurator.configure(context.environment)
  }

  lazy val router: Router = new Routes(
    httpErrorHandler,
    new UserController(userClient)
  )

  override lazy val injector: Injector = new SimpleInjector(NewInstanceInjector) +
    router + crypto + httpConfiguration + wsApi + global

} 
开发者ID:EVENFinancial,项目名称:play-compile-time-di-example,代码行数:43,代码来源:Application.scala

示例4: beforeEach

//设置package包名称以及导入依赖的类
package support

import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.{OneServerPerSuite, PlaySpec}
import play.api.db.slick.DatabaseConfigProvider
import play.api.inject.Injector
import slick.driver.JdbcProfile
import slick.driver.PostgresDriver.api._
import slick.jdbc.SQLActionBuilder
import slick.jdbc.SetParameter.SetUnit

import scala.concurrent.Await
import scala.concurrent.duration._

trait IntegrationSpec extends PlaySpec with OneServerPerSuite with BeforeAndAfterEach {

  import play.api.libs.concurrent.Execution.Implicits.defaultContext

  // Not super concerned about this because it is just a test helper.
  @SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements"))
  override def beforeEach() = cleanDatabase(app.injector)


  private def cleanDatabase(injector: Injector) = {
    val dbConfig = injector.instanceOf[DatabaseConfigProvider].get[JdbcProfile]
    val truncatesFuture = dbConfig.db.run(
      sql"""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name NOT IN ('schema_version');""".as[String]
    ).map {
      _.map { case tableName => SQLActionBuilder(List(s"ALTER TABLE $tableName DISABLE TRIGGER ALL;TRUNCATE TABLE $tableName;ALTER TABLE $tableName ENABLE TRIGGER ALL;"), SetUnit).asUpdate }
    }

    Await.result(truncatesFuture.flatMap(
      truncates =>
        dbConfig.db.run(
          DBIO.sequence(
            List(
              truncates
            ).flatten
          )
        )
    ), 5.seconds)
  }
} 
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:44,代码来源:IntegrationSpec.scala

示例5: RunnerConfigurationProvider

//设置package包名称以及导入依赖的类
package com.igorvovk.telegram.botapi.examples

import javax.inject.{Inject, Named, Provider, Singleton}

import akka.actor.{ActorSystem, Props}
import com.igorvovk.telegram.botapi._
import play.api.Configuration
import play.api.inject.Injector

@Singleton
class RunnerConfigurationProvider @Inject() (config: Configuration) extends Provider[RunnerConfiguration] {
  lazy val get = {
    val option = for {
      ns <- config.getConfig("telegram.runner")
      providerClass <- ns.getString("providerClass")
    } yield {
      RunnerConfiguration(
        providerClass = providerClass
      )
    }

    option.get
  }
}

case class RunnerConfiguration(providerClass: String)

class RunnerBotProvider @Inject() (runnerConfiguration: RunnerConfiguration, injector: Injector) extends Provider[Props] {
  def get() = {
    injector.instanceOf(getClass(runnerConfiguration.providerClass, classOf[Provider[Props]])).get()
  }

  private def getClass[T](className: String, instanceOf: Class[T]) = {
    Class.forName(className).asSubclass(instanceOf)
  }
}

class Bootstrap @Inject() (system: ActorSystem, client: TelegramApiClient, @Named("bot_from_config") bot: Props) {
  val logger = system.actorOf(SimpleMessageLoggerActor(), "message_logger")

  val gate: Props = ChatGateActor(client, ChatGateActorConfig(bot, messageLogger = Some(logger)))

  val emitter = system.actorOf(UpdatesEmitterActor(client), "emitter")
  val router = system.actorOf(PerChatMessageRouterActor(gate), "router")

  emitter ! UpdatesEmitterActor.AddSubscriber(router)
  emitter ! UpdatesEmitterActor.StartReceivingUpdates

} 
开发者ID:igorynia,项目名称:TelegramBotApi,代码行数:50,代码来源:Bootstrap.scala

示例6: connect

//设置package包名称以及导入依赖的类
package playdb

import com.typesafe.config.Config
import play.api.db._
import play.api.inject.{Injector, NewInstanceInjector}

import scala.util.control.NonFatal
import play.api.{Configuration, Environment, Logger}


  def connect(logConnection: Boolean = false): Unit = {
    databases foreach { db =>
      try {
        db.getConnection.close()
        if (logConnection) logger.info(s"Database [${db.name}] connected at ${db.url}")
      } catch {
        case NonFatal(e) =>
          // this is only an issue if initializeFailFast is true
          val dbConfig = configuration.get(db.name).get
          if(dbConfig.hasPath("hikaricp.initializationFailFast") && dbConfig.getBoolean("hikaricp.initializationFailFast")) {
            throw Configuration(configuration(db.name)).reportError("url", s"Cannot connect to database [${db.name}]", Some(e))
          }
          else {
            logger.info(s"Database [${db.name}] is not connected, but continuing anyway...")
          }
      }
    }
  }

  def shutdown(): Unit = {
    databases foreach (_.shutdown())
  }

}

object BetterDBApi {
  private val logger = Logger(classOf[BetterDBApi])
} 
开发者ID:njlg,项目名称:playdb,代码行数:39,代码来源:BetterDBApi.scala

示例7: get

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal.javadsl.api.broker

import javax.inject.{ Inject, Singleton }

import com.lightbend.lagom.javadsl.api.Descriptor.TopicCall
import com.lightbend.lagom.javadsl.api.broker.Topic
import play.api.inject.Injector

import scala.util.control.NonFatal


trait TopicFactoryProvider {
  def get: Option[TopicFactory]
}

@Singleton
class InjectorTopicFactoryProvider @Inject() (injector: Injector) extends TopicFactoryProvider {
  override lazy val get: Option[TopicFactory] = try {
    Some(injector.instanceOf[TopicFactory])
  } catch {
    case NonFatal(e) => None
  }
}

object NoTopicFactoryProvider extends TopicFactoryProvider {
  override val get = None
} 
开发者ID:lagom,项目名称:lagom,代码行数:28,代码来源:TopicFactory.scala

示例8: AppLoader

//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource

import controllers.EventsController
import controllers.UsersController
import io.getquill._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.evolutions.Evolutions
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.api.routing.sird._
import models.{Events, Users}

class AppLoader extends ApplicationLoader {
  override def load(context: Context): Application = new BuiltInComponentsFromContext(context) with DBComponents with HikariCPComponents {

    lazy val db = new JdbcContext[H2Dialect, SnakeCase](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])


    lazy val users = new Users(db)
    lazy val events = new Events(db)

    lazy val usersController = new UsersController(users)
    lazy val eventsController = new EventsController(events)

    val router = Router.from {
      case GET(p"/users/${long(id)}") => usersController.get(id)
      case POST(p"/users") => usersController.create
      case DELETE(p"/users/${long(id)}") => usersController.delete(id)
      case PUT(p"/users/${long(id)}") => usersController.update(id)
        // Events Routes
      case POST(p"/events") => eventsController.push
      case GET(p"/events/${long(id)}") => eventsController.get(id)
    }

    override lazy val injector: Injector =
      new SimpleInjector(NewInstanceInjector) + users + events + router + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + global

    Evolutions.applyEvolutions(dbApi.database("default"))

  }.application
} 
开发者ID:a605269,项目名称:play-multitenant,代码行数:45,代码来源:AppLoader.scala


注:本文中的play.api.inject.Injector类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。