Leiningen
在mac
下面,可以直接使用brew install leiningen
来安装lein
,当然lein
官方也提供了其他平台的安装方式,这里不再累述。
首先,我们建立一个工程,lein new clojure-stuff
,进入clojure-stuff
目录,我们可以看到项目的目录结构:
首先我们关注的就是project.clj
文件,我们在这个文件里面定义整个项目的一些基本属性:
(defproject clojure-stuff "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]])
“0.1.0-SNAPSHOT
“是该项目现在的版本情况,在clojure
里面,如果一个项目版本以“-SNAPSHOT
”结尾,通常表明改项目还处于开发阶段,还没有正式release
。
src
目录下面就是我们项目文件了,我们更改clojure_stuff/core.clj
文件:
(ns clojure-stuff.core)
(defn my-plus
[a b]
(+ a b))
(ns clojure-stuff.core)
声明了一个namespace
,然后我们定义了一个my-plus
函数,简单进行两个数相加,通常,如果我们定义了一个函数,最好在test
里面进行测试,所以我们在test/clojure_stuff/core_test.clj
里面编写如下代码:
然后执行lein test
,输出:
➜ clojure-stuff git:(master) ✗ lein test
lein test clojure-stuff.core-test
Ran 1 tests containing 1 assertions.
0 failures, 0 errors.
我们可以改动test
,让其报错:
(deftest my-plus-test
(is (= (my-plus 1 2) 2))))
如果项目需要能够直接运行,我们需要编写main
函数,在src/clojure_stuff/core.clj
里面,我们编写:
(defn -main
[& args]
(println "Hello Clojure"))
同时在project.clj
里面设置:
:main ^:skip-aot clojure-stuff.core
然后执行lein run
,得到:
我们可以使用lein unberjar
将项目生成一个jar
供其他工程使用:
➜ clojure-stuff git:(master) ✗ lein uberjar
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.
Created $(PATH)/src/clojure-stuff/target/clojure-stuff-0.1.0-SNAPSHOT.jar
Created $(PATH)/src/clojure-stuff/target/clojure-stuff-0.1.0-SNAPSHOT-standalone.jar