說明: 本文轉載自: 如何在 Leiningen 中使用本地 jar 文件
如果在 Leiningen 建立的項目中引用第三方的庫,在 project.clj 文件中 :dependencies 中指定庫名版本即可。http://clojars.org/上有豐富的庫可以直接用,并不是任何庫都可以找到,有時也需要在 Clojure 中引入本地的一個 .jar 文件,可以手動建個本地 Maven 倉庫來,不過 lein 里有個叫 lein-localrepo 的插件可以幫我們完成這個步驟。
為了演示,我先用 lein 命令創(chuàng)建一個叫hello的項目:
lein new hello
然后編輯 project.clj,添加以下:
:plugins [[lein-localrepo "0.5.4"]]
lein 會自動安裝 lein-localrepo 插件。
OK,現(xiàn)在我從 https://commons.apache.org/proper/commons-codec/download_codec.cgi 下載了 Apache 公共庫里的 Codec 庫,解壓后得到 commons-codec-1.9.jar 這個文件,我需要把它引入到當前 hello 項目中使用。
運行以下命名:
lein localrepo coords ~/commons-codec-1.9.jar
把運行后的輸出內容記下:
/home/lu4nx/commons-codec-1.9.jar commons-codec/commons-codec 1.9
第二列就是添加到 :dependencies 里的庫名,以及第三列的版本?,F(xiàn)在我們把它加入到 project.clj 中:
:dependencies [[org.clojure/clojure "1.6.0"]
[commons-codec/commons-codec "1.9"]]
然后,我們把 commons-codec-1.9.jar 添加到本地 Maven 倉庫中來:
lein localrepo install ~/commons-codec-1.9.jar commons-codec/commons-codec 1.9
注意最后兩個參數(shù),仍然是執(zhí)行 coords 輸出的內容,包名和版本號。
接下來運行以下命令,lein 自動解決依賴問題:
$ lein deps
執(zhí)行完畢后檢查 Classpath,看 commons-codec 是否可用:
$ lein classpath
/home/lu4nx/hello/test:/home/lu4nx/hello/src:/home/lu4nx/hello/dev-resources:/home/lu4nx/hello/resources:/home/lu4nx/hello/target/classes:/home/lu4nx/.m2/repository/clojure-complete/clojure-complete/0.2.3/clojure-complete-0.2.3.jar:/home/lu4nx/.m2/repository/org/clojure/tools.nrepl/0.2.6/tools.nrepl-0.2.6.jar:/home/lu4nx/.m2/repository/commons-codec/commons-codec/1.9/commons-codec-1.9.jar:/home/lu4nx/.m2/repository/org/clojure/clojure/1.6.0/clojure-1.6.0.jar
一般情況下,只要沒有報錯,都應該沒問題的,從輸出結果中已經(jīng)看到 commons-codec-1.9.jar 了,說明可用了,接著在 REPL 中嘗試調用這個庫:
$ lein repl
user=> (import '[org.apache.commons.codec.net URLCodec])
org.apache.commons.codec.net.URLCodec
user=> (.encode (URLCodec.) "哈哈")
"%E5%93%88%E5%93%88"