Scala中的环境具体配置 [英] specific config by environment in Scala

查看:240
本文介绍了Scala中的环境具体配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要专门为开发而设有不同的数据库,这是在Scala中设置项目的好方法。 测试生产环境(类似于Rails中的内容)

解决方案

使用类型安全配置。创建一个这样的Config对象:

  import com.typesafe.config._ 

object Config {
val env = if(System.getenv(SCALA_ENV)== null)developmentelse System.getenv(SCALA_ENV)

val conf = ConfigFactory.load()
def apply()= conf.getConfig(env)
}

然后创建 application.conf 文件在 src / main / resources 文件夹中:

 开发{
your_app {
databaseUrl =jdbc:mysql:// localhost:3306 / dev_db
databaseUser =xxxx
databasePassword =xxxx
}
}
test {
your_app {
databaseUrl =jdbc:mysql:// localhost:3306 / test_db
databaseUser =xxxxx
databasePassword =xxxx
}
}

现在从您应用程序的任何地方,您可以访问配置:



Config()。getString(your_app.databaseUrl)



如果你有你的环境设置(例如 export SCALA_ENV = test )当您运行应用程序时,会考虑正确的配置部分。缺省是开发


What is a good way to set up a project in Scala which uses different configuration depending on environments.

I need to specifically have different databases for development, test and production environment (similar to what is done in Rails)

解决方案

Use typesafe Config. Create a Config object like this:

import com.typesafe.config._

object Config {
  val env = if (System.getenv("SCALA_ENV") == null) "development" else System.getenv("SCALA_ENV")

  val conf = ConfigFactory.load()
  def apply() = conf.getConfig(env)
}

Then create the application.conf file in src/main/resources folder:

development {
  your_app {
    databaseUrl = "jdbc:mysql://localhost:3306/dev_db"
    databaseUser = "xxxx"
    databasePassword = "xxxx"
  }
}
test {
  your_app {
    databaseUrl = "jdbc:mysql://localhost:3306/test_db"
    databaseUser = "xxxxx"
    databasePassword = "xxxx"
  }
}

Now from anywhere in your application, you can access configuration:

Config().getString("your_app.databaseUrl")

If you have your environment set up (e.g. export SCALA_ENV=test) when you run your application, it will consider the right configuration section. The default is development

这篇关于Scala中的环境具体配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆