如何使用 SBT 在 运行 任务中动态地 'inject' 文件中定义的环境变量

How to dynamically 'inject' environment variables defined in a file in run task with SBT

我正在寻找一种从动态文件向 SBT 任务注入环境变量的方法。

例如:sbt run -devsbt dev:runsbt dev run在注入文件conf/env/database.dev[=22]中定义的环境变量后启动sbt 运行任务=]

目前我在 build.sbt 中有这段代码:

// ...
val dev = taskKey[Unit]("Dev config")
val local = taskKey[Unit]("Local config")

def setEnvVar(env: String) = {
  try{
    val split: Array[String] = (s"cat conf/env/database.$env" !!).split("\n")
    val raw_vars = split.map(_.span(! _.equals('='))).map(x => x._1 -> x._2.tail).toList
    raw_vars foreach (v => {
      println(s"INJECTING ${v._1} = ${v._2}")
      javaOptions += s"-D${v._1}=${v._2}"
    })
  }catch{
    case e: Exception => println(s"Cannot inject env vars (${e.getMessage})")
  }
}


dev := {
  setEnvVar("dev")
}

local := {
  setEnvVar("local")
}

当我启动 sbt dev run 时,我得到以下结果:

[info] Loading project definition from ...
[info] Set current project to ...
INJECTING PG_DB = qgd
INJECTING PG_HOST = localhost
INJECTING PG_PORT = 5432
INJECTING PG_USERNAME = ...
INJECTING PG_PASSWORD = ...
[success] Total time: 0 s, completed 12 févr. 2016 10:46:10

--- (Running the application, auto-reloading is enabled) ---

[info] p.c.s.NettyServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Ctrl+D to stop and go back to the console...)

但是,当我转到 localhost:9000 时,我可以看到没有注入变量。

在我的 application.conf 中:

// ...
pg.db               = ${?PG_DB}
pg.host             = ${?PG_HOST}
pg.port             = ${?PG_PORT}
pg.default.username = ${?PG_USERNAME}
pg.default.password = ${?PG_PASSWORD}
// ...

你有办法解决我的问题吗?

正如@AjayPadala 所建议的,我使用 fork 进程解决了我的问题。

我刚刚用以下代码更新了我以前的代码:

fork := true // <=======================

val dev = taskKey[Unit]("Dev config")
val local = taskKey[Unit]("Local config")

def setEnvVar(env: String) = {
  try{
    val split: Array[String] = (s"cat conf/env/database.$env" !!).split("\n")
    val raw_vars = split.map(_.span(! _.equals('='))).map(x => x._1 -> x._2.tail).toList
    val sysProp = System.getProperties // <=======================
    raw_vars foreach (v => {
      println(s"INJECTING ${v._1} = ${v._2}")
      sysProp.put(v._1, v._2) // <=======================
    })
    System.setProperties(sysProp) // <=======================
  }catch{
    case e: Exception => println(s"Cannot inject env vars (${e.getMessage})")
  }
}


dev := {
  setEnvVar("dev")
}

local := {
  setEnvVar("dev.default")
}