运行具有外部依赖项的Scala脚本

时间:2011-06-14 22:24:31

标签: java bash scala scripting jvm

我在/Users/joe/.scala/lib下面有以下jar:

commons-codec-1.4.jar       
httpclient-4.1.1.jar        
httpcore-4.1.jar
commons-logging-1.1.1.jar   
httpclient-cache-4.1.1.jar  
httpmime-4.1.1.jar

下面是我用scala编写的test.sh。

#!/bin/sh -v
L=`cd /Users/joe/.scala/lib;pwd`
cp=`echo $L/*.jar|sed 's/ /:/g'`
echo $cp
exec scala -classpath $cp $0 $@
!#
println(new org.apache.commons.httpclient.HttpClient())

这是我得到的错误:

$ ./test.sh 
#!/bin/sh -v
L=`cd /Users/joe/.scala/lib;pwd`
cd /Users/joe/.scala/lib;pwd
cp=`echo $L/*.jar|sed 's/ /:/g'`
echo $L/*.jar|sed 's/ /:/g'
echo $cp
/Users/joe/.scala/lib/commons-codec-1.4.jar:/Users/joe/.scala/lib/commons-logging-1.1.1.jar:/Users/joe/.scala/lib/httpclient-4.1.1.jar:/Users/joe/.scala/lib/httpclient-cache-4.1.1.jar:/Users/joe/.scala/lib/httpcore-4.1.jar:/Users/joe/.scala/lib/httpmime-4.1.1.jar
exec scala -classpath $cp $0 $@
/Users/joe/Desktop/scala/./test.sh:7: error: object httpclient is not a member of package org.apache.commons
println(new org.apache.commons.httpclient.HttpClient())
                               ^
one error found

但是,没有任何类路径依赖的简单工作虽然有效: hello.sh

#!/bin/sh
exec scala "$0" "$@"
!#

println(new java.util.Date())

知道我在第一个例子中做错了什么吗?或者,在使用scala脚本时,设置类路径依赖关系的最佳方法是什么?

2 个答案:

答案 0 :(得分:10)

我不会回答你的问题,但你可能会对此感兴趣。

假设您下载并安装SBT(版本0.10.0或更高版本),并创建一个名为“scalas”的shell脚本:

java -Dsbt.main.class=sbt.ScriptMain \
     -Dsbt.boot.directory=/home/user/.sbt/boot \
     -jar sbt-launch.jar "$@"

然后你就像这样编写你的脚本:

#!/usr/bin/env scalas
!#

/***
scalaVersion := "2.9.1"

libraryDependencies ++= Seq(
  "commons-codec" % "commons-codec" % "1.4", 
  "org.apache.httpcomponents" % "httpclient" % "4.1.1",
  "org.apache.httpcomponents" % "httpcore" % "4.1",
  "commons-logging" % "commons-logging" % "1.1.1",
  "org.apache.httpcomponents" % "httpclient-cache" % "4.1.1", 
  "org.apache.httpcomponents" % "httpmime" % "4.1.1"
)
*/

println(new org.apache.http.client.DefaultHttpClient())

答案 1 :(得分:4)

我认为4.1.1的类是org.apache.http.client.HttpClient而不是org.apache.commons.httpclient,它是一个接口。所以你可能想要

new org.apache.http.client.DefaultHttpClient()

而不是

new org.apache.commons.httpclient.HttpClient()

在早期版本中可能会有所不同。