当前位置:网站首页>Gradle knowledge generalization

Gradle knowledge generalization

2022-07-06 23:34:00 GeorgeLin98

Gradle brief introduction

Gradle background :

  • When there was no project management tool in the early days , For the third-party package that the project depends on : Copy third party jar Package to local , Then join in lib Under the table of contents , The disadvantages of doing so are self-evident , Management is complex and easy to conflict .
  • Ant:2000 Released in , pure java To write
  • Maven:2004 Released in , use pom.xml Management project
  • Gradle:2012 year ,google An endorsed project management tool

Gradle brief introduction :

  • Gradle Is an open source automated build tool , Support multilingual environment , suffer Ant、Maven The influence of thought , Combine the two , comparison Ant Nonstandard ,Maven Complex configuration of 、 There are many life cycle restrictions ,Gradle Both standardized and more flexible , have access to DSL( Domain specific language , Such as Groovy) Write build , The script is more refined . This course is based on Gradle7 Explain .
  • advantage :
    ① flexibility : be relative to Maven、Ant And so on ,Gradle A series of API Let's have the ability to modify or customize the project build process .
    ② Granularity : Source code compilation , Compilation of resources , One by one Task Of , We can modify it task To achieve fine control .
    ③ Extensibility :Gradle Support plug-in mechanism , So we can reuse these plug-ins , It is as simple and convenient as reusing libraries .
    ④ Compatibility :Gradle Not only is it powerful , And it can be compatible with all Maven、Ant function , in other words ,Gradle Absorbed the strengths of all construction tools .
    ⑤Spring Source code uses Gradle Conduct management
  • Inferiority :
    ① Each version has very big changes compared with the last one , There is no better upward compatibility .
    ② High learning cost ,groovy Scripting language
  • Gradle form :
     Insert picture description here

Gradle Installation configuration :

  • Address : Download from the official website
  • Download and unzip it to the local :
    ①binary-only edition (-bin suffix ): Only executable files
    ②complete edition (-all suffix ): In addition to the executable file, it also contains Gradle Source code and source code documentation
  • Decompress after downloading , Configure environment variables :
    ① newly build GRADLE_HOME environment variable , take gradle Root configuration
    ② stay path Add item %GRADLE_HOME%\bin, Be similar to JDK or Maven Configuration of
    ③ open CMD, perform gradle -v, The successful output of the version indicates that the installation and configuration are complete
  • Be careful : In real work, due to different versions of various projects , Will not use local configuration gradle, instead wrapper By .

Gradle Detailed explanation :

  • Gradle in 2 Big object :Project and Task.
    ① A component script is a project, Any one of them Gradle Builds are made up of one or more project form , You can put one project Compare to one pom Module or a jar, every last project It's all one groovy Script files .
    ②task As the name suggests, it is a task , It is Gradle The smallest execution unit in , Similar to a method or function function , Such as compiling 、 pack 、 Generate javadoc etc. , One project There will be more than one tasks.

Gradle structure Web

establish Gradle project :

  • Manually create :
    ① perform gradle init Create project
  • Quickly build (https://start.spring.io/):
    ①Gradle Version of SpringBoot
    ②Maven Version of SpringBoot

Project structure analysis :

├─build.gradle                        ①
├─gradlew                             ②
├─gradlew.bat						  ③
├─settings.gradle                     ④
├─gradle                              ⑤
│  └─wrapper                          
│      ├─ gradle-wrapper.jar          
│      ├─ gradle-wrapper.properties   
└─src                                 ⑥
    ├─main                            
    └─test
  • 1. The configuration file to be read when the project is automatically compiled . For example, specify the dependent package of the project .build.grade There are two , One is global , One is in the module . Overall build.grade The main setting is to declare the warehouse source ,gradle Version number description of .
  • 2.linux Under the gradle Environment script , It can be executed gradle Instructions , Such as :./gradlew build.
  • 3.windows Under the gradle Environmental Science , It can be executed gradle Instructions .
  • 4. Include some necessary settings , for example , Lazy relationship between tasks or projects, etc , No matter how many sub modules , The file will only have one , And it must be in the root project .
  • 5. contain wrapper Folder and its 2 Sub file , Role is : It can be installed automatically gradle Environmental Science .
  • 6. Program source code .

build.gradle infrastructure :

/********  Ordinary procedure  gradle init initialization  ******/
plugins {
    // Apply the java plugin to add support for Java
    id 'java'
    ...
}
repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}
dependencies {
    implementation 'com.google.guava:guava:27.1-jre'
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.4.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.4.2'
}
application {
    mainClassName = 'first.init.App'
}
test {
    useJUnitPlatform()
}

/******** SpringBoot  Project basic configuration  ******/
plugins {
	id 'org.springframework.boot' version '2.6.4'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'
}

group = 'com.it235'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
	useJUnitPlatform()
}
  • mavenCentral() and jCenter() difference :
    ①mavenCentral:Maven The central warehouse ,http://repo1.maven.org/maven2/, from Sonatype Services provided by the company . It is Apache Maven、SBT And other default warehouses for building systems , And can be easily Apache Ant/Ivy、Gradle And other tools . Open source organizations such as Apache Software foundation 、Eclipse The foundation 、JBoss And many individual open source projects release components to the central warehouse . maven The central warehouse has banned content browsing , Can be found in http://search.maven.org/ Query component .
    ②jCenter: By JFrog Provided by the company Bintray Medium Java Warehouse . It is currently the largest in the world Java and Android Open source software component warehouse . All content is distributed through the content distribution network (CDN) Use encryption https Connect to get .JCenter yes Goovy Grape Default warehouse in ,Gradle Built in support (jcenter() Warehouse ), Very easy to use in ( Except maybe Maven In addition to the ) Configure in other build tools .
    JCenter comparison mavenCenter More components , Better performance . But some components only exist mavenCenter in .

IDE Use Gradle:

  • Settings—》Gradle You can configure the gradle_home, But if you configure subsequent use, you will go through a lot of holes , because IDEA Will be used by default gradle-wrapper Download content of , Let's talk about the general configuration first , Here's the picture :
     Insert picture description here
     Insert picture description here
  • But when you import the project, you will find , The program will download one wrapper dependent zip package :
     Insert picture description here
  • Why is this so ? Follow maven It seems different , This Wrapper What is the function of ?
    ①Gradle-Wrapper It's simplification Gardle Installation and deployment of , The starting point is to allow arbitrary gradle No separate installation environment is required for any project , The project will automatically identify whether there is an environment , If you don't find a connection with wrapper.properties The same version Gardle,IDEA Will help you download one gradle Environmental Science , The official starting point is good , Now let's understand the meaning of these configurations .
# distributionBase and distributionPath It's a combination of , Appoint gradle Storage location after decompression 
# GRADLE_USER_HOME Represents the user directory ,
	# windows System :c:\window\<user-name>\.gradle\
	# linux yes $HOME/.gradle
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists

#  Specify a version gradle Download address 
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip

# zipStoreBase and zipStorePath In combination with , Specify Download gradle.zip Storage location ;
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Groovy elements of grammar

Groovy brief introduction :

  • Groovy It's based on JVM Dynamic language , His grammar and Java be similar , In the end, it's also about compiling .class stay JVM Up operation .Groovy Fully compatible with Java And on this basis, many dynamic types and flexible features are added , For example, support closure , Support DSL( Domain specific language ), Is a very flexible dynamic scripting language .
  • To execute groovy Script of must be installed groovy Environmental Science , Or use Java Of ClassLoader To call .
  • Address :Groovy Environment installation download link
  • Recommended download 3.0 edition , After downloading, it is recommended to put C Discoid C:\Program Files\groovy\ Under the table of contents , And configuration GROOVY_HOME and Path that will do

Groovy Detailed explanation :

Engineering Project

Project brief introduction :

  • stay gradle in , every last build.gradle The file corresponds to a Project example , We are build.gradle Content written in , Equivalent to Project Instance properties or methods .
  • During build initialization ,Gradle The steps of instantiation are as follows :
    ① Create a for the entire build Settings example , One Settings An instance is a settings.gradle file
    ② in the light of Settings Instance configuration , Scan and analyze the configuration according to the configuration level settings.gradle Medium project.( among settings The most important attribute in is include)
    ③ For each project Corresponding build.gradle Do the initial , And create Project example ( This loading project The order of is according to the previous configuration level , That is, breadth scan loading , This ensures that after the parent module is loaded , The submodule will be loaded )
  • A complete project It consists of the following objects ( In fact, it only consists of attributes and methods ):
     Insert picture description here

attribute :

  • Built in attributes can be assigned directly , There is no need to declare :
group = 'com.it235'
version = '1.0.0'
  • Custom attributes can be used groovy grammar , with java Grammar combination :
//groovy Defining attributes 
def pname = "projectName:" + project.name

//java Type reception 
String pname = "projectName:" + project.name
  • Use ext Name space to extend attributes , You can define it in project、task、subproject Read and update :
ext.prop1 = "it"
ext.prop2 = " Programming "
  • Attribute scope :
    ① When reading and writing attributes ,Project It will be searched in the following order , The attribute will be returned when it is found in a certain range . If not found , It throws an exception .
    <1>Project The object itself . The attributes in this range include Project The implementation class defines getters and setters Method . such as :project.getName() The method corresponds to name attribute . The readability of these attributes depends on whether they are defined getters perhaps setters Method .
    <2>Project Of ext attribute ( extra ) . Every Project Will maintain a mapping of additional attributes , It can contain any name -> It's worth it . After the definition , The properties of this scope are readable and writable . such as :project.ext.prop1 = ‘it’ .
    <3> Added to... Through plug-ins Project Extended properties in ( extensions ) . Each extension can be used as a read-only attribute , Its name is the same as the extension . such as :project.android.compileSdkVersion .
    <4> Add to by plug-in Project Convention properties in ( convention ) . Plugins can be accessed through Project Of Convention Object to Project Add properties and methods to . The readability and writability of the attributes of this range depend on the constraint object .
    <5>Project in Tasks . have access to Task The name of is accessed as the attribute name task. The properties of this range are read-only .
    <6>ext The properties and convention properties of are inherited from the parent of the project , Recurse to the root project . The properties of this range are read-only .
  • frequently-used project attribute :
Property name describe
allprojects A collection containing this project and its subprojects .
buildDir Compilation directory of the current project ( Automatic generation ) The default value is porjectDir/build
defaultTasks The default task name set of the current project , These default tasks will be executed when the current build does not provide a task name
group The group name of the current project
logger The logger of the current project , Can be used in build Write a log in the file
name The name of this project
parent The parent project of this project
path The absolute path of this project
project At present project Object instances
rootDir The root directory of this project . The root directory is the project directory of the root project
rootProject The root in the current project hierarchy project
subprojects A collection of subprojects of the current project
tasks This project task aggregate .
version Version of this project

Method :

  • Method scope :
    ①Project The object itself
    ②build.gradle Script files
    ③ Add to by plug-in Project The extension ( extensions ) . Each extension can be treated as a closure or Action Methods .
    ④ The agreed method of adding plug-ins to the project ( convention ) . Plug ins can be accessed through the Convention Object to add properties and methods to the project .
    ⑤ In the project Tasks . Every Task Will add a method , The method name is the task name , Parameters are single closures or Action . This method uses the provided closure to call Task.configure( groovy.lang.Closure ) Method .
  • frequently-used Project Method :
Method describe
afterEvaluate You can add a closure , It will be implemented immediately after the project is evaluated . When executing the build file belonging to the project , Will notify such listeners .
allprojects Configure the current project and each of its subprojects
apply Apply zero or more plug-ins or scripts .
beforeEvaluate Add a closure , It will be implemented immediately before the project starts evaluation
configure Configure object collections through closures .
copy Copy the specified file
defaultTasks Set the name of the default task for this project . Use these when the task name is not provided at the beginning of the build .
delete Delete files and directories
exec Execute external command
file Resolve the file path relative to the project directory of the project
findProject Locate the project by path . If the path is relative , Then explain relative to the project .
findProperty Find a specific attribute , If not found , Returns the value of the given property or null
getAllTasks Return to the map of the tasks contained in this project
hasProperty Determine whether this item has the given attribute
javaexec perform Java The main class
javaexec Execute external Java process .
mkdir Create a directory and return a file pointing to it .
property Returns the value of the given property . The location attributes of this method are as follows :
setProperty Set the properties of this item . This method searches for the attribute with the given name in the following location , And set the attribute to the first position where it finds the attribute .
subprojects Configure the subprojects of this project
task establish Task With the given name a And add it to this project
uri Resolve the file path to URI, Project directory relative to the project
  • Examples of common methods :
    ①buildscript{}: Configuration of the current gradle The build information or dependencies that the script itself needs to use
    ②configurations{}: Configure the use of declared dependencies for specific purposes
    ③repositories{}: Warehouse configuration
    ④dependencies{}: stay gradle in dependencies{} First class citizen , It describes the configurations{} The third-party resources that the group depends on .
    ⑤allprojects{}: Configure the dependencies required by this project and each of its subprojects . Generally, in the multi module project scenario, we will configure the common part of the root project allprojects in .
    ⑥subprojects{}: Sub module configuration
    ⑦sourceSets{}: Configure source code information
    ⑧artifacts{}: Configure the product component information to be delivered
    ⑨publishing{}:deploy Current project to warehouse

The task of Engineering

Mission profile :

  • The task is gradle The smallest execution unit of , One build.gradle It's a series of task form , The importance is self-evident .

Engineering plug-in

Plug in introduction :

  • Plugins can encapsulate a series of tasks , for example compile , test , Packing, etc .IDEA、VsCode、Eclipse、Maven、Chrome And so on are tools that support plug-in integration . Plug ins mean extensions ,Gradle Just define the plug-in specification , Major manufacturers or individual developers can develop many useful plug-ins by following this specification , So as to enrich Gradle ecology .
  • Nowadays, several plug-ins with very high rating are used :SpringBoot Build plug-ins ,Docker Container integration plug-in ,junit Unit test plug-ins, etc

The life cycle of Engineering

Life cycle :

  • Gradle The core of is a dependency based programming language , There is a certain dependency between tasks , And each task will be executed only once . At build time ,Gradle These tasks will be connected to form a directed acyclic graph . that Gradle When did the series connection take place ? This requires a full understanding Gradle What has been done at each stage , The series of actions from the beginning to the end is called the life cycle .
  • gradle Built with 3 Different stages :
    ① initialization : gradle Support single project and multi project construction , In this phase ,gradle Can parse setting.gradle file , Determine which projects need to be involved in the build , And create a Project example .
    ② To configure : When the initialization phase is completed , It will enter the configuration stage , The configuration phase resolves all project Medium build.gradle File to get all task, Execute dependencies after forming a directed acyclic graph , And all project Medium build script Part and task The configuration section of will call ( Note that it is not specific task Code ).
    ③ perform task: When the task dependency graph is completed , Gradle You're ready for everything , Then enter the implementation phase . According to the directed acyclic graph task The order of the list , Execute all assigned task.

summary

complete build.gradle:

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: "war"
// Statement 
apply plugin: "com.jfrog.bintray"
apply plugin: 'org.akhikhl.gretty' //gradle + jetty  The server tomcat

/**
 * buildscript {}  It's a build tool Gradle The resources you need , Not for our application , It can be stated that maven Libraries and plug-ins depend on 
 *  Such as : This block contains gradle-plugin Dependence , Because this plug-in contains Gradle structure APP Additional commands required by the module . 
 */
buildscript {
    /**
     * repositories {}  Area configuration Gradle Used to download the dependent warehouse address .
     * Gradle Remote warehouses with built-in support include JCenter、Maven Central  and  Ivy,4.1 Version starts to have built-in support google(). 
     *  You can also use the local warehouse or configure our own remote warehouse address .
     *  The following code example Gradle Use JCenter As a code warehouse for finding dependent libraries .
     */
    repositories {
        maven {url "https://maven.aliyun.com/repository/public"}
        jcenter()
    }

    /**
     * dependencies {}  Regional Configuration Gradle compile APP Engineering needs to rely on .
     *  The following code shows path dependency 3.1.0 edition gradle-plugin
     */
    
	dependencies {
		classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.0"
		classpath 'org.akhikhl.gretty:gretty:+'
	}
}

// Only buildscript  and  pluginManagement In front of it 
plugins {
    // Core plug-ins ,gradle Provide 
    id 'java'
    id 'eclipse'
    id 'war'
    // Non core plug-ins ( Community plug-ins ), Must pass id+version The way to constrain 
    id 'com.bmuschko.docker-remote-api' version '6.7.0'
    id 'com.jfrog.bintray' version '1.8.5'
}

//gav  coordinate 
group 'com.it235'
version '1.0.0'

sourceCompatibility = 1.8
targetCompatibility = 1.8

/**
 * allprojects {}  The area can configure the code warehouse and dependencies used by all modules in the project , Such as , Third party plug-ins or libraries .
 *  If it's a single project, you don't need to use allprojects Closure ,, Direct will repositories Write it under the root node 
 */
allprojects {
   repositories {
       maven { url 'https://maven.aliyun.com/repository/jcenter' }
	   maven { url 'https://maven.aliyun.com/repository/google' }
	   maven { url 'https://maven.aliyun.com/repository/central' }
	   maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
	   google()
	   jcenter()
   }
}

/**
 * subprojects {}  The area can configure the code warehouse and dependencies used by all sub modules in the project , Such as , Third party plug-ins or libraries .
 *  And allprojects Corresponding , Less use scenarios 
 */
subprojects {
   repositories {
       jcenter()
   }
}

test{
	useJUnitPlatform()
}

task cleanx() {
	println "Hello Gradle"
	//Groovy grammar ,Gradle It's really powerful , Too flexible , So the cost of getting started is very high , This is also why others say that Maven Good place ,Maven XML The expansion ability is too poor 
}

Gradle Directory and Idea To configure :

  • Use Gradle from Use this list to configure... For your project Gradle edition ( To configure Gradle working directory ). You can choose one of the following options :
    ’gradle-wrapper.properties’ file: This is the use of Gradle Recommended default options for wrappers . under these circumstances , You can use Gradle Version updates are delegated to Gradle And automatically download this version of Gradle. This option also allows you to use precise Gradle Build version . Gradle The version is saved in the project gradle In the directory gradle-wrapper.properties In file , Can help you eliminate any Gradle Version of the problem .
    ’wrapper’ task in Gradle build script: Select this option to configure according to the wrapper task configuration Gradle Wrappers . If you want to control which... To use in your project Gradle edition , It might be convenient . If you use the default Gradle Wrapper options , And then switch to Gradle Wrapper task configuration , The changes you make in the task will be automatically updated during project import .
    Specified location: If you don't want to use Gradle Wrappers , Instead, you want to manually download and use specific Gradle edition , Please select this option . Specify your Gradle Installation position .
  • To configure Gradle User home directory :Gradle By default C:\Users\Administrator.gradle As Gradle The warehouse directory is used to store global configuration properties and initialization scripts, as well as cache and log files .
    ① Generally speaking, it is not configured in C disc , So you can Idea Pass through Gradle User Home Specify additional configurations on other disks . You can create a new directory or specify it as Maven Local directory for .
  • Configured correctly IDEA Make in Terminal Execute with gradlew(gradle wrapper) Beginning commands and operations are graphical IDEA Use Gradle The version is the same version .
    ①GRADLE_USER_HOME It refers to the environment variables you need to configure . This environment variable determines the execution project/gradle/gradle-rapper.jar Download when project/gradle/gradle-wrapper.properties Version specified in gradle Storage location of . Enter in the command line with gradlew The command that begins with will use GRADLE_USER_HOME Specify the location of the environment variable to store the downloaded gradle.
    ②Gradle user home refer to IDEA About China gradle Configuration of , This configuration refers to IDEA The use of , When you are in IDEA Click on the gradle Related graphic buttons , for example gradle Buttons for building tasks or Enable-AutoImport Button will be used Gradle user home Download from the specified directory project/gradle/gradle-wrapper.properties designated gradle edition .
  • link :IDEA How to correctly configure Gradle? GRADLE_USER_HOME and Gradle user home The difference between
原网站

版权声明
本文为[GeorgeLin98]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061550262054.html