The basics of Gradle learning

content

concept

Gradle is a project automation build tool. Anyone who has used Ant and Maven build tools knows that they build scripts in the form of xml, while Gradle is encapsulated into a method-style configuration build script through the Groovy language;

Install

1. Install JDK

2. Download Gradle and install it

3. Configure the environment variable java -version to view the JDK version, and gradle -v to view the gradle version;

The above installation is very simple

If the development tool you use is Android Studio, you only need to install JDK. Android Studio comes with gradle installed.

Groovy

Here I would like to briefly introduce the concept of Groovy. What is Groovy? Groovy is an agile dynamic language (DSL) for the Java virtual machine, an object-oriented programming language, and a scripting language with simple code writing rules, including closures and other features of general dynamic languages;

Groovy 与 Java

  • Fully compatible with Java syntax;
  • Methods and classes are public by default;
  • The compiler will automatically add get/set methods to properties;
  • Attributes can be obtained by directly using dots, similar to static variables in java;
  • The value of the last expression is the return value;
  • There will be no null pointer errors;
  • A semicolon is not required;

characteristic

  • assert statement can be executed anywhere;
  • The type does not have to be clearly defined, and the attribute type is defined according to the assignment type;
  • You can call the method without the parentheses;

  • Three expressions for strings: "string" 'string' "'string"'

The difference between the three ways:

'':单纯的字符串;
"":可以插入变量,比如:
    def a = world
    "hello ${a} !!!"
'''''':字符串可以换行,比如:
'''hello
world
!!!'''
  • gather

    list is equivalent to Arraylist in java

def list = ['java','gradle','groovy']
list << 'c#' //追加到list中

调用方法:list[0]

map is equivalent to java's LinkHashMap

def map = ['javaver':1.8,'gradlever':4.1]
map.groovy=2.4.15 // 追加元素

调用方法:map.javaver
  • Closure (a simple understanding of closure is that an internal method is defined inside a method, and this internal method is improved for external use)
def m1 = {
    p > print p
}

def m2 = {
    print 'world'
}

def m3(Closure closure){
    closure('hello')
}

def m4(Closure closure){
    closure()
}

调用:
m3(m1)
m4(m2)

build script

building blocks

There are two basic concepts in gradle construction: project (project), task (task), each building block contains at least one project, and the project contains one or more tasks. In a multi-project build, a project can depend on other projects, and tasks can also form a dependency graph to ensure their execution order.

dependent process

Interpretation: TaskA in Project1 depends on TaskB, TaskB depends on TaskC, TaskD in Project2 depends on TaskE, TaskE depends on TaskF, and Project1 depends on Project2, so the build order should be TaskF-EDCBA;

  • Project

Concept: A project represents a component (such as: jar, aar, etc.) that is being built. After the build is started, gradle will instantiate an org.gradle.api.Project object based on build.gradle, and can make it implicit through the project variable Available, scripts such as variables and methods written in build.gradle will run in this project object;
what is an implicit call? Take a chestnut:

在build.gradle中

group 'com.ailian.test' 这个就是隐式调用

原版应该是:
project.group = 'com.ailian.test'

attribute:
group group

name name, a group cannot have the same name

version version number, build the version number of the project

Through the above three attributes, an object can be uniquely determined;

  如:依赖gson的写法:
  compile 'com.google.code.gson:gson:2.8.4'
  compile group:'com.google.code.gson',name:'gson',version:'2.8.4'

  group : com.google.code.gson
  name : gson
  verson : 2.8.4

method:

apply apply plugin

dependencies

reprositories repository

task task

Other configuration methods of properties: ext, gradle.properties (key-value pair way to define properties)

  • task

Concept: Task corresponds to org.gradle.api.Task. It mainly includes task actions and task dependencies. A task action defines a minimal unit of work that can be defined to depend on other tasks, the order in which actions are executed, and the conditions for execution.

method:

dependsOn declares task dependencies

doFirst task performed at the top of the task list
doLast or << task performed at the end of the task list

A task list can execute multiple doFirst and doLast methods

build life cycle

  • Initialize
    Initialize the projects that need to be involved in the build
  • Configure the dependency order and execution order of the
    generated tasks
  • Execute
    Execute action code

image

dependency management

Almost all JVM-based software projects need to rely on external class libraries to reuse existing functions. Automatic dependency management can clarify the version of dependencies and resolve version conflicts caused by transitive dependencies.

  • Common warehouse

    Public repository: You can upload dependency packages and download dependency packages

    mavenCentral :search.maven.org

    jcenter :https://jcenter.bintray.com/

    google

    Private repository: mavenLocal local existing dependencies

    Custom Warehouse: Warehouse within the company

如:build.gradle中的配置
repositories{
 maven{
      url "https://oss.sonatype.org/content/repositories/snapshots"//自定义仓库地址
  }
  mavenLocal()
  mavenCentral()
  jcenter()

}
根据上面的配置顺序会依次从上面的仓库查找依赖包,找到为止,找不到则报错
  • transitivity of dependencies

    B depends on A, C depends on B, then C depends on A

    It is precisely because of the transitivity of versions that there will be a problem of dependency conflicts.

比如:
B依赖A:1.2版本
C依赖A:1.3版本
D依赖B和C
根据依赖的传递性,D依赖A,这时A有两个版本1.21.3,这时候就出现了冲突

image
From another perspective, dependency transitivity can minimize existing dependencies and avoid dependency version conflicts; for
example, module A depends on the Gson package, and the main project B depends on the A module, and the main project B does not need to depend on the Gson package alone.

Ways to resolve version conflicts:

1. Eliminate transitive dependencies

 dependencies{
     compile('com.jakewharton.rxbinding2:rxbinding-design:2.0.0'){
     exclude group: 'com.android.support'
    } 
 }


 编译rxbinding-design时排除依赖包“com.android.support”

2. Force a version to be specified

configurations.all{
    resolutionStrategy{
        force 'com.android.support:appcompat-v7:26.0.0'
    }
}
项目中所有使用com.android.support:appcompat-v7的包都强制使用26.0.0的版本

Multi-project build

In real project development, the package hierarchy and class relationship are complex, so it is necessary to split the code into modules at this time, and the split modules can build a complete project through gradle's dependency management;

Module composition

A runnable project will inevitably have a root proejct, other Moudles are Subprojects, and each Moudle including the root project has a build.gradle configuration file.

image

The rootproject's build.gradle can define common configuration items for all subprojects:

rootproject的build.gradle:

allprojects{//所有subprojects的build.gradle公共定义方法
    repositories {//定义所有subprojects都使用这个公共仓库
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

You can define your own configuration without subproject;

Build the release of the project

As the saying goes, Lele alone is not as good as Lele. We have written good tools, which naturally need to be shared. The projects we build and process (such as jar packages) can be automatically published to public warehouses or other private server warehouses through gradle, and shared with others used by developers;

Gradle does not have its own warehouse, so it uses the maven warehouse;

If you need to publish to a remote public warehouse, you need to register the corresponding warehouse account, and after publishing, you need to approve it before it can be used by other developers. The steps for gradle configuration release:


apply plugin:'maven-publish'

publishing{
    publications{
        huoPublish(MavenPublication){
            from components.java
        }
    }
    repositories{
        maven{
            name ""//项目名称
            url ""//发布地址
        }
    }
}

Summary In order
to efficiently develop high-quality projects, we need to learn to use various development tools, but also to understand the working principles and usage methods of these efficient development tools. It is good for us to develop projects. Here is just the basic part of accepting gradle. , gradle has many other higher-level uses, and interested students can study it more deeply;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325581358&siteId=291194637