当我已经在项目中添加依赖项时,为什么必须将jar添加到类路径才能运行jar文件?

时间:2020-02-14 12:58:16

标签: scala intellij-idea sbt intellij-scala

我正在使用SBT作为构建工具在IntelliJ上进行Scala项目。我最近开始工作sbt build。 这是我的项目结构: enter image description here

这是我的build.sbt文件:

name := "AnalyzeTables"
version := "0.1"    
scalaVersion := "2.11.8"

// https://mvnrepository.com/artifact/org.postgresql/postgresql
libraryDependencies += "org.postgresql" % "postgresql" % "42.1.4"

// https://mvnrepository.com/artifact/commons-codec/commons-codec
libraryDependencies += "commons-codec" % "commons-codec" % "1.13"

// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
libraryDependencies += "org.apache.commons" % "commons-lang3" % "3.8.1"

// https://mvnrepository.com/artifact/log4j/log4j
//libraryDependencies += "log4j" % "log4j" % "1.2.17"

我的代码中包含Class.forName(“ org.postgresql.Driver)以连接到数据库并进行查询。与此同时,我在代码中添加了密码解密和记录程序。 我正在以以下格式运行jar:

scala <jarname> <argument I use in my code>

这里的问题是,如果我只是按照上面提到的方式提交,我会看到Postgres驱动程序的ClassNotFoundException。因此,我将其添加到jar的类路径中,并如下提交。

scala -cp /path/postgresql-42.1.4.jar <jarname> <argument I use in my code>

现在我得到了Logger的异常。所以我再次将其添加到classpath中,它变成:

scala -cp /path/postgresql-42.1.4.jar:/path/log4j-1.2.17.jar <jarname> <argument I use in my code>

现在我得到了commons编解码器的例外,因此我也添加了它。 斯卡拉-cp /path/postgresql-42.1.4.jar:/path/log4j-1.2.17.jar:/path/commons-codec-1.13.jar

现在该jar运行正常,我可以看到结果。 因此,我将依赖项添加到了build.sbt文件中。我还做了以下操作:

project structure -> Modules -> Dependencies -> + -> jars -> Add all the missing jars that are giving problems

如果我删除所有的-cp参数,并用公正的scala <jarname> <argument>提交jar,它将再次返回ClassNotFoundException到postgres jar。 那么,在build.sbt文件中添加依赖项,然后再次将其添加到类路径中又有什么意义呢? 是否有我所缺少的设置?还是看错了方向?

编辑: 提出建议后,我创建了一个新项目,并将所有代码复制到其中,并将插件addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.5")添加到了我在目录/ project /中创建的新文件plugins.sbt文件中,如下图所示。 enter image description here

我可以在sbt-plugins目录中看到该插件。但是,当我再次构建jar并导出时,它仍然显示11kb jar,而不是胖jar。

0 个答案:

没有答案
相关问题