groovy语言可用作DSL,现在,使用groovy语言编写配置文件也越来越流行。
刚开始阅读groovy语言DSL方式的写法时,那真叫一个看不懂。
gradle是运行在groovy之上的一个项目构建工具。请看如下使用groovy语言写成的gradle配置文件build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.6.RELEASE")
}
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
testCompile("mysql:mysql-connector-java:5.1.25")
}
我们来从groovy语法上理解下上述配置文件的含义。
首先调用了buildscript方法,这个方法的参数是个闭包,这个闭包就是紧随buildsrcipt之后的大括号。
在这个闭包中,依次调用了repositories、dependencies两个方法。在reponsitories方法的闭包中调用了mavenCentral方法,
在dependencies方法的闭包中调用了classpath方法。
再来看下,最后一个dependencies方法。在这个方法的闭包中,首先调用了compile方法,这个compile方法也可以写成:
compile("org.springframework.boot:spring-boot-starter-web", {exclude module: "spring-boot-starter-tomcat"})
这个方法有两个参数,一个是字符串"org.springframework.boot:spring-boot-starter-web",另一个是紧随其后的闭包。
在紧随其后的这个闭包中,调用了exclude方法,这个方法的参数是module: "spring-boot-starter-tomcat",这个方法的参数是个Map对象,这个Map对象中有一个键值对,这个键值对的键是module,值是"spring-boot-starter-tomcat"。
现在我们再来看一个使用groovy编写的Spring配置文件:
beans {
//beanName(type)
dataSource(BasicDataSource) {
//注入属性
driverClassName = "org.hsqldb.jdbcDriver"
url = "jdbc:hsqldb:mem:grailsDB"
username = "sa"
password = ""
settings = [mynew:"setting"]
}
sessionFactory(SessionFactory) {
//注入属性,引用其他Bean
dataSource = dataSource
}
myService(MyService) {
//使用闭包定义嵌套的Bean
nestedBean = { AnotherBean bean ->
dataSource = dataSource
}
}
}