Leiningen

    mac下面,可以直接使用brew install leiningen来安装lein,当然lein官方也提供了其他平台的安装方式,这里不再累述。

    首先,我们建立一个工程,lein new clojure-stuff,进入clojure-stuff目录,我们可以看到项目的目录结构:

    首先我们关注的就是project.clj文件,我们在这个文件里面定义整个项目的一些基本属性:

    1. (defproject clojure-stuff "0.1.0-SNAPSHOT"
    2. :description "FIXME: write description"
    3. :url "http://example.com/FIXME"
    4. :license {:name "Eclipse Public License"
    5. :url "http://www.eclipse.org/legal/epl-v10.html"}
    6. :dependencies [[org.clojure/clojure "1.7.0"]])

    0.1.0-SNAPSHOT“是该项目现在的版本情况,在clojure里面,如果一个项目版本以“-SNAPSHOT”结尾,通常表明改项目还处于开发阶段,还没有正式release

    src目录下面就是我们项目文件了,我们更改clojure_stuff/core.clj文件:

    1. (ns clojure-stuff.core)
    2. (defn my-plus
    3. [a b]
    4. (+ a b))

    (ns clojure-stuff.core)声明了一个namespace,然后我们定义了一个my-plus函数,简单进行两个数相加,通常,如果我们定义了一个函数,最好在test里面进行测试,所以我们在test/clojure_stuff/core_test.clj里面编写如下代码:

    然后执行lein test,输出:

    1. clojure-stuff git:(master) lein test
    2. lein test clojure-stuff.core-test
    3. Ran 1 tests containing 1 assertions.
    4. 0 failures, 0 errors.

    我们可以改动test,让其报错:

    1. (deftest my-plus-test
    2. (is (= (my-plus 1 2) 2))))

    如果项目需要能够直接运行,我们需要编写main函数,在src/clojure_stuff/core.clj里面,我们编写:

    1. (defn -main
    2. [& args]
    3. (println "Hello Clojure"))

    同时在project.clj里面设置:

    1. :main ^:skip-aot clojure-stuff.core

    然后执行lein run,得到:

    我们可以使用lein unberjar将项目生成一个jar供其他工程使用:

    1. clojure-stuff git:(master) lein uberjar
    2. Warning: The Main-Class specified does not exist within the jar. It may not be executable as expected. A gen-class directive may be missing in the namespace which contains the main method.
    3. Created $(PATH)/src/clojure-stuff/target/clojure-stuff-0.1.0-SNAPSHOT.jar
    4. Created $(PATH)/src/clojure-stuff/target/clojure-stuff-0.1.0-SNAPSHOT-standalone.jar