轻松理解gradle配置和Groovy语法

轻松理解gradle配置和Groovy语法,第1张

做过java开发或者android开发,你一定使用gradle,这也是现代大部分项目使用的项目构建和项目依赖管理的工具。

用过很多年,也知道怎么用,但就是不知道为什么要那么写,gradle的各种花式配置,到底怎么是什么意思呢,要怎么理解这些写法呢?

比如以下的gradle配置(android项目的gradle配置)

要理解这些,必须先搞清楚Groovy语法,gradle正是基于Groovy来实现的。

Groovy是一种DSL(Domain Specific Languages)特定领域语言,一般只用在特定领域

怎么去理解Groovy语言呢?

废话少说,先写个hello world!

如果你用的是 idea 工具,一般 tools菜单下都一个 Groovy Console

打开以后,什么都没有。

这是这样:

6、创建一个对象,跟java语法类似

现在我们可以来重新理解一下gradle中写的哪些玩意了

比如文章开始贴的gradle配置 :

附上完整的demo例子

** 1.2.1 创建项目结构 **

在项目的根目录下面新建一个文件夹,名为buildSrc,然后依次新建子目录

src/main/groovy,然后可以建自己的包名,这里以demo.gradle.task为例,依次新建

子目录demo/gradle/task,然后在buildSrc根目录下面新建build.gradle文件,里面写入:

最终目录结构如下:

编译之后变成下面的样式:

** 1.2.2 编写task**

在demo.gradle.task包中,新建一个task类,名为HelloGradleTask.groovy,

注意在sayHello方法上的那个@TaskAction注解的作用。

** 1.2.3 使用task**

在项目中的build.gradle中添加如下脚本:

重新编译项目,在项目下面就会多了一个名为myCustomTask的task,执行task,

会打印########## custom task ###########和"Hello Gradle Custom Task"

两句话。

以上,为自定义task的所有方式。总的来说,如果只是自己项目中要使用,

第一二钟方式就满足了,然后根据task的复杂度来选择使用哪种方式。

下面是配置范例 build.gradle:

apply plugin: 'groovy'

repositories {

mavenLocal()

    mavenCentral()

}

dependencies {

    compile 'org.codehaus.groovy:groovy-all:2.3.7'

compile 'org.apache.ant:ant:1.9.4'

    testCompile 'junit:junit:4.11'

testCompile 'commons-io:commons-io:2.2'

}

sourceSets {

    main {

        groovy {

srcDirs = ['./src/main/groovy']

include 'Main.groovy'

        }

    }

    test {

        groovy {

            srcDirs = ['./src/test/groovy']

        }

    }

}

task runScript(type: JavaExec) {

  description 'Run Groovy script'

  // Set main property to name of Groovy script class.

  main = 'Main'

  // Set classpath for running the Groovy script.

  classpath = sourceSets.main.runtimeClasspath

}

defaultTasks 'runScript'

Main.groovy

import groovy.util.Node

import groovy.xml.XmlUtil

public class Main{

public static final String LINE_SEPARATOR = System.getProperty("line.separator")

boolean extractPassword(Node root, def map){

boolean update = false

String beanId 

String propertyName

for(def entry: map.entrySet()){

beanId = entry.key.split('_')[0]

propertyName = entry.key.split('_')[-1]

def node = root.find{ it."@id" == beanId }.find{ it."@name" == propertyName }

String password = node.attribute("value")

if( password ==~ /\$\{.*?\}/ ){

println "It's already a place-holder of Spring style. Skip."

continue

}

node."@value" = '${' + entry.key + '}'

entry.value = password

update = true

//println XmlUtil.serialize(node)

}

return update

}

void saveXml(String fileName, Node xml){

def writer = new FileWriter(fileName)

def printer = new XmlNodePrinter(new PrintWriter(writer))

printer.preserveWhitespace = true

printer.print(xml)

}

void saveSstsConfiguration(String fileName, def map){

File file = new File(fileName)

Properties props = new Properties()

file.withInputStream{ stream ->

     props.load(stream)    

}

boolean update = false

map.entrySet().each{ entry->

if(props[entry.key] == null){

if( !(entry.value ==~ /\$\{.*?\}/) ){

file.append(LINE_SEPARATOR + "${entry.key}=${entry.value}")

update = true

}

}

}

if(update){

file.append(LINE_SEPARATOR)

}

}

static main(args){

Main obj = new Main()

String fileName = "./src/main/resources/Spring-Config.xml"

def map = ["database_password":"", "sybase_password":""]

File file = new File(fileName)

Node root = new XmlParser().parseText(file.getText())

boolean update = obj.extractPassword(root, map)

if(update){

new AntBuilder().copy( file:fileName, tofile:fileName + "_Bak")

obj.saveXml(fileName, root)

String sstsConfiguration = "./src/main/resources/ssts.configuration"

new AntBuilder().copy( file:sstsConfiguration, tofile:sstsConfiguration + "_Bak")

obj.saveSstsConfiguration(sstsConfiguration, map)

}else{

println "No update and no replication."

}

println map

}

}

MainTest.groovy

import org.junit.*

import static org.junit.Assert.*

import org.apache.commons.io.FileUtils

import groovy.util.AntBuilder

import groovy.xml.XmlUtil

import groovy.util.Node

import org.apache.commons.io.FileUtils

class MainTest {

private obj = null

static final String input = '''<beans xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <bean id="database" class="org.apache.commons.dbcp.BasicDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

    <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=gbk"/>

    <property name="username" value="root"/>

    <property name="password" value="sa"/>

  </bean>

  <bean id="sybase" class="org.apache.commons.dbcp.BasicDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

    <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=gbk"/>

    <property name="username" value="root"/>

    <property name="password" value="ind_suezssts"/>

  </bean>

</beans>

'''

static final String target = '''<beans xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <bean id="database" class="org.apache.commons.dbcp.BasicDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

    <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=gbk"/>

    <property name="username" value="root"/>

    <property name="password" value="${database_password}"/>

  </bean>

  <bean id="sybase" class="org.apache.commons.dbcp.BasicDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

    <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=gbk"/>

    <property name="username" value="root"/>

    <property name="password" value="${sybase_password}"/>

  </bean>

</beans>

'''

static def map = null

    static Node root 

static Node xml

@BeforeClass

public static void enter(){

}

@Before

public void setUp(){

root = new XmlParser().parseText(input)

xml = new XmlParser().parseText(target)

obj = new Main()

map = ["database_password":"", "sybase_password":""]

}

@Test

public void extractPasswordReturnTrue(){

boolean result = obj.extractPassword(root, map)

def mymap = ["database_password":"sa", "sybase_password":"ind_suezssts"]

assertTrue result

assertEquals mymap,map

assertEquals XmlUtil.serialize(xml), XmlUtil.serialize(root)

}

@Test

public void extractPasswordReturnFalse(){

Node myxml = new XmlParser().parseText(target)

boolean result = obj.extractPassword(xml, map)

def mymap = ["database_password":"", "sybase_password":""]

assertFalse result

assertEquals mymap,map

assertEquals XmlUtil.serialize(myxml), XmlUtil.serialize(xml)

}

@Test

public void saveXml(){

//String fileName, Node xml

String fileName = "./src/test/resources/test-A.xml"

new File(fileName).delete()

obj.saveXml(fileName, xml)

assertTrue new File(fileName).exists()

Node myxml = new XmlParser().parseText(new File(fileName).getText())

assertEquals XmlUtil.serialize(myxml), XmlUtil.serialize(xml)

}

// void saveSstsConfiguration(String fileName, def map){

@Test

public void saveSstsConfiguration(){

String fileName = "./src/test/resources/ssts.configuration.test"

String fileTarget = "./src/test/resources/ssts.configuration.target"

new File(fileName).write("")

boolean result = obj.extractPassword(root, map)

obj.saveSstsConfiguration(fileName, map)

assertEquals(FileUtils.readLines(new File(fileName)), FileUtils.readLines(new File(fileTarget)))

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11412660.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存