Groovy安装与入门实例

1 Groovy是什么?


来看下官网的介绍:http://groovy.codehaus.org

===============================================================================

Groovy...

·is an agile anddynamic languagefor theJava Virtual Machine

·builds upon the strengths of Javabut hasadditionalpower featuresinspiredby languages like Python, Ruby and Smalltalk

·makesmodern programming featuresavailable to Java developers withalmost-zero learning curve

·provides the ability tostatically type checkandstaticallycompileyour codefor robustness and performance

·supportsDomain-Specific Languagesand other compact syntax so your codebecomeseasyto read and maintain

·makes writing shell and buildscripts easy with itspowerfulprocessing primitives, OO abilities and an Ant DSL

·increases developer productivity byreducing scaffolding codewhen developing web, GUI, database orconsole applications

·simplifies testingbysupporting unit testing and mocking out-of-the-box

·seamlesslyintegrates with all existingJava classes and libraries

·compiles straight to Java bytecodeso you can use it anywhere you can use Java

===============================================================================

通过支持DSL提高代码可读性和可维护性

减少开始Web、GUI、数据库、控制台应用程序时的脚手架代码

简化单元测试和Mock技术

与Java类包无缝集成

2 Groovy环境安装


下面是官方文档中摘取的安装步骤。适用于Linux系统或Cygwin模拟环境。如果是Windows平台的话,也可以直接下载Windows installer一键安装。

===============================================================================

GVM (the GroovyenVironment Manager)

This tool makesinstalling Groovy on any Bash platform (Mac OSX, Linux, Cygwin, Solaris orFreeBSD) very easy.

Simply open a newterminal and enter:

$ curl -s get.gvmtool.net | bash

Follow theinstructions on-screen to complete installation.

Open a newterminal or type the command:

$ source "$HOME/.gvm/bin/gvm-init.sh"

Then install thelatest stable Groovy:

$ gvm install groovy

After installationis complete and you've made it your default version, test it with:

$ groovy -version

That's all thereis to it!

===============================================================================

下面来亲自体验一下,然后编写个Groovy版的Hello World测试一下。

$ curl –s get.gvmtool.net | bash


之后执行初始化脚本,也可以将这句命令加入到~/.bashrc中。

$ source "/cygdrive/c/Users/daichen/.gvm/bin/gvm-init.sh"

编写一个Hello World试一下吧。

helloworld.groovy

===============================================================================

class Test {

def text = “helloworld!!!”

}

print new Test().getText()

===============================================================================

$ groovy helloworld.groovy

hello world!!!

3 Groovy-Eclipse插件安装


在Help -> Install New Software下输入http://dist.springsource.org/release/GRECLIPSE/e3.6

选择Groovy-Eclipse (Required) 进行安装。

可以新建Groovy项目,或者在已有项目中新加Groovy Class,就会自动开启此项目上的Groovy Nature属性。这样普通Java代码就与Groovy代码融合在一起了。