1

我有办法isDevelopmentMode从外部访问值ScalatraServlet吗?它似乎来自ScalatraKernel特性,那么包括它是一个可行的选择吗?

我想要实现的是让 DI 配置知道我是处于开发模式还是生产模式,以便能够配置数据库设置。我目前正在为 DI 使用Subcut

4

1 回答 1

3

我将 scalatra servlet 中的开发模式设置为 config/system 属性值

object AppEnv {
  private val cloader = getClass.getClassLoader

  val PRODUCTION = "production".intern
  val DEVELOPMENT = "development".intern
  val STAGING = "staging".intern
  val TEST = "test".intern

  lazy val environment = readEnvironmentKey(println _)

  def isProduction = isEnvironment(PRODUCTION)
  def isDevelopment = isEnvironment(DEVELOPMENT)
  def isStaging = isEnvironment(STAGING)
  def isTest = isEnvironment(TEST)
  def isEnvironment(env: String) = environment.toLowerCase(Locale.ENGLISH) == env.toLowerCase(Locale.ENGLISH)

  def readEnvironmentKey(failWith: String ⇒ Unit = _ ⇒ null) = {
    (ep("BACKCHAT_MODE") orElse sp("backchat.mode")) getOrElse {
      val inferred = "development"
      failWith("no environment found, defaulting to: " + inferred)
      inferred
    }
  }

  private def sp(key: String) = {
    val s = System.getProperty(key)
    if (s != null && s.trim.nonEmpty) Some(s) else None
  }
  private def ep(key: String) = {
    val s = System.getenv(key)
    if (s != null && s.trim.nonEmpty) Some(s) else None
  }
}

trait ApplicationModes extends ScalatraKernel {
  override def environment: String = AppEnv.environment
  override def isDevelopmentMode = environment != AppEnv.PRODUCTION && environment != AppEnv.STAGING
}

Scalatra 还允许您使用 System 属性来设置该模式,您可以读取该属性并获得类似的结果。-Dorg.scalatra.environment=发展

于 2011-11-03T09:31:20.163 回答