我正在阅读此示例,该示例向我展示了如何使用Slick-CodeGen生成源代码
https://github.com/slick/slick-codegen-example/blob/master/build.sbt
虽然这个示例很好,我想修改它,以便它使用typesafe配置从application.conf读取数据库配置。
否则我将在此处以及application.conf文件中复制数据库连接配置。
有谁知道,如何修改此示例以便我们可以使用typesafe配置从application.conf读取配置值?
编辑:根据以下建议,我尝试了以下
我在项目文件夹
中创建了一个名为build.sbt
的文件
libraryDependencies += "com.typesafe" % "config" % "1.3.1"
将我的main build.sbt文件(在项目根目录中)修改为
val slickVersion = "3.1.1"
lazy val mainProject = Project(
id = "FooBar",
base=file("."),
settings = Defaults.coreDefaultSettings ++ Seq(
scalaVersion := "2.11.8",
libraryDependencies ++= Seq(
"com.typesafe.slick" %% "slick" % slickVersion,
"com.typesafe.slick" %% "slick-codegen" % slickVersion,
"mysql" % "mysql-connector-java" % "5.1.35",
"com.typesafe" % "config" % "1.3.1"
),
myConf := {
ConfigFactory.parseFile(new File("src/main/resources/application.conf"))
},
slick <<= slickCodeGenTask,
sourceGenerators in Compile <+= slickCodeGenTask
)
)
lazy val slick = TaskKey[Seq[File]]("gen-tables")
lazy val myConf = settingKey[Config]("The application properties")
lazy val slickCodeGenTask = (sourceManaged, dependencyClasspath in Compile, runner in Compile, streams) map {(dir, cp, r, s) =>
val outputDir = (dir / "slick").getPath
val username = myConf.value.getString("mysql.username")
val password = myConf.value.getString("mysql.password")
val port = myConf.value.getInt("mysql.port")
val db = myConf.value.getString("mysql.db")
val server = myConf.value.getString("mysql.server")
val url = s"jdbc:mysql://$server:$port/$db?username=$username&password=$password"
val jdbcDriver = myConf.value.getString("mysql.jdbcDriver")
val slickDriver = myConf.value.getString("mysql.slickDriver")
val pkg = "sql"
val fname = outputDir + "/db/Tables.scala"
toError(r.run("slick.codegen.SourceCodeGenerator", cp.files, Array(slickDriver, jdbcDriver, url, outputDir, pkg), s.log))
Seq(file(fname))
}
但它无法解析Config和ConfigFactory类。
答案 0 :(得分:2)
在project/build.sbt
中声明对Typesafe配置的依赖:
libraryDependencies += "com.typesafe" % "config" % "1.3.1"
并在build.sbt
中定义保存配置文件的设置:
lazy val myConf = settingKey[Config]("The application properties")
myConf := {
ConfigFactory.parseFile(new File("src/main/resources/application.conf"))
}
现在,您可以使用myConf.value.getString("xyz")
来获取其他任务或设置中的配置值。