我是Scala的新手,我正在尝试开发一个使用自定义库的小型项目。我在库中创建了一个mysql连接池。这是我的图书馆的 build.sbt
organization := "com.learn"
name := "liblearn-scala"
version := "0.1"
scalaVersion := "2.12.6"
libraryDependencies += "mysql" % "mysql-connector-java" % "6.0.6"
libraryDependencies += "org.apache.tomcat" % "tomcat-dbcp" % "8.5.0"
我已使用sbt publishLocal
将其发布到本地常春藤仓库中
现在我有一个项目,该项目将使用上述 build.sbt
的库name := "SBT1"
version := "0.1"
scalaVersion := "2.12.6"
libraryDependencies += "com.learn" % "liblearn-scala_2.12" % "0.1"
我能够编译新项目,但是当我运行它时,我会得到
java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSource
但是,如果我添加
libraryDependencies += "mysql" % "mysql-connector-java" % "6.0.6"
libraryDependencies += "org.apache.tomcat" % "tomcat-dbcp" % "8.5.0"
在项目的build.sbt中可以正常工作。
这是使用Scala-sbt的实际方法吗?即:我还必须在项目内部提及自定义库的依赖关系?
这是我的图书馆代码(我只有1个文件)
package com.learn.scala.db
import java.sql.Connection
import org.apache.tomcat.dbcp.dbcp2._
object MyMySQL {
private val dbUrl = s"jdbc:mysql://localhost:3306/school?autoReconnect=true"
private val connectionPool = new BasicDataSource()
connectionPool.setUsername("root")
connectionPool.setPassword("xyz")
connectionPool.setDriverClassName("com.mysql.cj.jdbc.Driver")
connectionPool.setUrl(dbUrl)
connectionPool.setInitialSize(3)
def getConnection: Connection = connectionPool.getConnection
}
这是我的项目代码:
try {
val conn = MyMySQL.getConnection
val ps = conn.prepareStatement("select * from school")
val rs = ps.executeQuery()
while (rs.next()) {
print(rs.getString("name"))
print(rs.getString("rank"))
println("----------------------------------")
}
rs.close()
ps.close()
conn.close()
} catch {
case ex: Exception => {
println(ex.printStackTrace())
}
}
答案 0 :(得分:2)
By default SBT fetches all project dependencies, transitively. This means it should be necessary to explicitly declare only liblearn-scala
, and not also the transitive dependencies mysql-connector-java
and tomcat-dbcp
. Transitivity can be disabled, and transitive dependencies can be excluded, however unless this has been done explicitly, then it should not be the cause of the problem.
Without seeing your whole build.sbt
, I believe you are doing the right thing. If sbt clean publishLocal
is not solving the problem, you could try the nuclear option and clear the whole ivy cache (note this will force all projects to re-fetch dependencies).