2010-08-02 31 views
5

我有一个hello.clj如下。如何在运行由'lein uberjar'创建的jar时设置类路径?

(ns hello) 
(defn hi [] (println "HI")) 

通常,我可以在main.clj中使用这个函数,如下所示。 hello.clj位于包含main.clj的同一目录中。类路径包括。 (当前路径)。

(use 'hello) 
(hi) 

如何使用hello.clj作为'lein uberjar'?

我用'lein new myproject; lein deps'来获得以下结构。

 
. 
|-- README 
|-- classes 
| `-- myproject 
|-- lib 
| |-- clojure-1.2.0-beta1.jar 
| |-- clojure-contrib-1.2.0-beta1.jar 
| `-- lucene-core-3.0.2.jar 
|-- project.clj 
|-- src 
| `-- myproject 
|  `-- core.clj 
`-- test 
    `-- myproject 
     `-- test 
      `-- core.clj 

project.clj如下。

(defproject myproject "1.0.0-SNAPSHOT" 
    :description "FIXME: write" 
    :dependencies [[org.clojure/clojure "1.2.0-beta1"] 
       [org.clojure/clojure-contrib "1.2.0-beta1"] 
       [org.apache.lucene/lucene-core "3.0.2"]] 
    :main myproject.core)  

而core.clj如下。

(ns myproject.core 
    (:gen-class)) 

(use 'hello) 

(defn test1 [] (println "hello")) 

(defn -main [& args] 
    (do 
    (println "Welcome to my project! These are your args:" args) 
    (test1) 
    (hi))) 

现在,我在哪里把hello.clj? 我试图将其复制到myproject/src目录并运行uberjar来获取jar。但是,运行jar会导致此错误消息。

 
prosseek:myproject smcho$ java -jar myproject-1.0.0-SNAPSHOT-standalone.jar a d d 
Exception in thread "main" java.lang.ExceptionInInitializerError 
Caused by: java.io.FileNotFoundException: Could not locate hello__init.class or hello.clj on classpath: (core.clj:0) 
... 
  • 可能是什么问题?错误消息说hello.clj不在类路径上。但是,如何用'lein uberjar'设置类路径?

我上传了项目here

回答

8

你把hello.clj在src/myproject的所以它的NS应该myproject.hello。有了这个文件结构,我希望hello.clj可以说(ns myproject.hello),core.clj可以说(use 'myproject.hello)

当我做这些改变,我得到:

$ java -jar myproject-standalone.jar a b c 
Welcome to my project! These are your args: (a b c) 
hello 
HI 
+0

是的,它的工作原理!非常感谢。 – prosseek 2010-08-02 20:57:46

+1

你想要做什么(ns hello)被称为单段命名空间。尽管当你刚刚进入Clojure-land时它可以正常工作,但是一旦执行了AOT以便可以作为uberjar启动,myproject.core就会变成Java字节码,并且由于它没有Java包,因此无法访问hello名称空间。 – technomancy 2010-08-13 17:55:31

0

clj应该在你的project-root/src里面。有了它,它应该工作。有关类似项目的示例,请参阅leiningen项目。柳叶刀命名空间是内源:

http://github.com/technomancy/leiningen/tree/master/src/

+0

我误解你的问题有点:)是的,如果你有兴趣,使为hello项目的一部分,是的,你把它里面。/src/myproject和declar ethe命名空间作为myproject.hello。但是如果你正在使用另一个项目中的另一个命名空间(比如leiningen中使用的lancet),那么将hello.clj放入其自己的命名空间并在/src下添加的方法也可以。 – 2010-08-03 03:14:38