gradle 教程学习笔记

Posted 夜宿山寺

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了gradle 教程学习笔记相关的知识,希望对你有一定的参考价值。

今天继续学习gradle的命令,首先可以用idea 建立一个gradle的项目,然后会默认生成一段脚本,在这个脚本里面我引用了spring框架。首先来说一下具体的命令

  

-?, -h, --help          Shows this help message.
-a, --no-rebuild        Do not rebuild project dependencies.
-b, --build-file        Specifies the build file.
-C, --cache             Specifies how compiled build scripts should be cached. Possible values are: 'rebuild' and 'on'. Default value is 'on' [deprecated - Use '--rerun-tasks' or '--recompile-scripts' instead]
-c, --settings-file     Specifies the settings file.
--configure-on-demand   Only relevant projects are configured in this build run. This means faster build for large multi-project builds. [incubating]
--continue              Continues task execution after a task failure.
-D, --system-prop       Set system property of the JVM (e.g. -Dmyprop=myvalue).
-d, --debug             Log in debug mode (includes normal stacktrace).
--daemon                Uses the Gradle daemon to run the build. Starts the daemon if not running.
--foreground            Starts the Gradle daemon in the foreground. [incubating]
-g, --gradle-user-home  Specifies the gradle user home directory.
--gui                   Launches the Gradle GUI.
-I, --init-script       Specifies an initialization script.
-i, --info              Set log level to info.
-m, --dry-run           Runs the builds with all task actions disabled.
--no-color              Do not use color in the console output.
--no-daemon             Do not use the Gradle daemon to run the build.
--no-opt                Ignore any task optimization. [deprecated - Use '--rerun-tasks' instead]
--offline               The build should operate without accessing network resources.
-P, --project-prop      Set project property for the build script (e.g. -Pmyprop=myvalue).
-p, --project-dir       Specifies the start directory for Gradle. Defaults to current directory.
--parallel              Build projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use. [incubating]
--parallel-threads      Build projects in parallel, using the specified number of executor threads. [incubating]
--profile               Profiles build execution time and generates a report in the <build_dir>/reports/profile directory.
--project-cache-dir     Specifies the project-specific cache directory. Defaults to .gradle in the root project directory.
-q, --quiet             Log errors only.
--recompile-scripts     Force build script recompiling.
--refresh               Refresh the state of resources of the type(s) specified. Currently only 'dependencies' is supported. [deprecated - Use '--refresh-dependencies' instead.]
--refresh-dependencies  Refresh the state of dependencies.
--rerun-tasks           Ignore previously cached task results.
-S, --full-stacktrace   Print out the full (very verbose) stacktrace for all exceptions.
-s, --stacktrace        Print out the stacktrace for all exceptions.
--stop                  Stops the Gradle daemon if it is running.
-u, --no-search-upward  Don't search in parent folders for a settings.gradle file.
-v, --version           Print version info.
-x, --exclude-task      Specify a task to be excluded from execution.
 以上便是通过--help调用出来的命令,一般情况下来说用到的命令也不会太多,首先是

命令一:gradle build

用这个命令运行下面的脚本就会把项目构建成一个jar包,例如我的Test项目编译后的jar包名字叫做Test-1.0.jar ,首部采用了java的插件,在这个插件里面其实定义了很多任务,只不过是看不见默认调用了而已

//采用java的插件
apply plugin: 'java' 


sourceCompatibility = 1.5
//设置项目版本
version = '1.0'
//设置仓库
repositories 
    mavenCentral()

//设置测试编译时候的依赖包
dependencies 
    testCompile group: 'junit', name: 'junit', version: '4.11'


你在build的时候其实他会默认加上一些命令,他会自己加入以下这些命令,左右看看命令名称应该就能够知道了

:processResources UP-TO-DATE     
:classes                 
:jar UP-TO-DATE      
:assemble UP-TO-DATE      
:compileTestJava UP-TO-DATE      
:processTestResources UP-TO-DATE      
:testClasses UP-TO-DATE      
:test UP-TO-DATE      
:check UP-TO-DATE      
:build UP-TO-DATE      
               

可以通过这个构建工具加入一些额外的依赖包比如可以用spring的,执行build之后会自动去下载依赖包,但是idea 好像有缓存有时候不能够显示出来或者加载,等会就能看见效果 ,下面的jar那个括号里面是为了打包的时候zaijava的manifest加入一些说明


apply plugin: 'java'

sourceCompatibility = 1.5
version = '1.0'

repositories 
    mavenCentral()


dependencies 
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'org.springframework:spring-context:4.1.1.RELEASE'

jar
    manifest
        attributes "title": "gradle start",
                    "version":version
    
在运行之后你就可以看见你的jar包里面的manifest文件内容变化了

Manifest-Version: 1.0
title: gradle start
version: 1.0

命令二: gradle properties

那其实build为什么这神奇,是因为他自己定义需要任务和属性,可以通过上面的命令进行查看,下面是列出这些默认的属性

allprojects: [root project 'Test']
ant: org.gradle.api.internal.project.DefaultAntBuilder@51288417
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@60cf62ad
apiDocTitle: Test 1.0 API  
archivesBaseName: Test     
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler@1e0895f5
asDynamicObject: org.gradle.api.internal.ExtensibleDynamicObject@1ac4ccad
assemble: task ':assemble' 
binaries: [classes 'main', classes 'test']
build: task ':build'       
buildDependents: task ':buildDependents'
buildDir: /Users/mac_wk/IdeaProjects/Test/build
buildFile: /Users/mac_wk/IdeaProjects/Test/build.gradle
buildNeeded: task ':buildNeeded'
buildScriptSource: org.gradle.groovy.scripts.UriScriptSource@14982a82
buildTasks: [build]        
buildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@4ee5b2d9
check: task ':check'       
childProjects:           
class: class org.gradle.api.internal.project.DefaultProject_Decorated
classes: task ':classes'   
clean: task ':clean'       
compileJava: task ':compileJava'
compileTestJava: task ':compileTestJava'
components: [org.gradle.api.internal.java.JavaLibrary@72f8ae0c]
configurationActions: org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@323f3c96
configurations: [configuration ':archives', configuration ':compile', configuration ':default', configuration ':runtime', configuration ':testCompile', configuration ':testRuntime']
convention: org.gradle.api.internal.plugins.DefaultConvention@6726cc69
defaultArtifacts: org.gradle.api.internal.plugins.DefaultArtifactPublicationSet_Decorated@4b6d92e
defaultTasks: []           
dependencies: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@33899f7a
dependencyCacheDir: /Users/mac_wk/IdeaProjects/Test/build/dependency-cache
dependencyCacheDirName: dependency-cache
dependsOnProjects: []      
depth: 0                   
description: null          
distsDir: /Users/mac_wk/IdeaProjects/Test/build/distributions
distsDirName: distributions
docsDir: /Users/mac_wk/IdeaProjects/Test/build/docs
docsDirName: docs          
ext: org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension@7899de11
extensions: org.gradle.api.internal.plugins.DefaultConvention@6726cc69
fileResolver: org.gradle.api.internal.file.BaseDirFileResolver@290d10ef
gradle: build 'Test'       
group:                     
implicitTasks: [task ':dependencies', task ':dependencyInsight', task ':help', task ':projects', task ':properties', task ':tasks']
inheritedScope: org.gradle.api.internal.ExtensibleDynamicObject$InheritedDynamicObject@1bc0d349
jar: task ':jar'           
javadoc: task ':javadoc'   
libsDir: /Users/mac_wk/IdeaProjects/Test/build/libs
libsDirName: libs          
logger: org.gradle.api.logging.Logging$LoggerImpl@644ded04
logging: org.gradle.logging.internal.DefaultLoggingManager@5292ceca
manifest: org.gradle.api.java.archives.internal.DefaultManifest@13d9261f
metaClass: org.codehaus.groovy.runtime.HandleMetaClass@e9ef5b6[groovy.lang.MetaClassImpl@e9ef5b6[class org.gradle.api.internal.project.DefaultProject_Decorated]]
metaInf: []                
modelRegistry: org.gradle.model.internal.DefaultModelRegistry@5300cac
module: org.gradle.api.internal.artifacts.ProjectBackedModule@24b52d3e
name: Test                 
parent: null               
parentIdentifier: null     
path: :                    
plugins: [org.gradle.api.plugins.HelpTasksPlugin@6d467c87, org.gradle.api.plugins.BasePlugin@1a35993f, org.gradle.api.plugins.ReportingBasePlugin@518cf84a, org.gradle.language.base.plugins.LanguageBasePlugin@1be59f28, org.gradle.language.jvm.plugins.JvmLanguagePlugin@2ab2710, org.gradle.api.plugins.JavaLanguagePlugin@149f5761, org.gradle.api.plugins.JavaBasePlugin@c6e0f32, org.gradle.api.plugins.JavaPlugin@4554de02]
processResources: task ':processResources'
processTestResources: task ':processTestResources'
project: root project 'Test'
projectDir: /Users/mac_wk/IdeaProjects/Test
projectEvaluationBroadcaster: ProjectEvaluationListener broadcast
projectEvaluator: org.gradle.configuration.project.LifecycleProjectEvaluator@4110765e
projectRegistry: org.gradle.api.internal.project.DefaultProjectRegistry@1ba359bd
properties: ...          
rebuildTasks: [clean, build]
reporting: org.gradle.api.reporting.ReportingExtension_Decorated@62e93c3a
reportsDir: /Users/mac_wk/IdeaProjects/Test/build/reports
reportsDirName: reports    
repositories: [org.gradle.api.internal.artifacts.repositories.DefaultMavenArtifactRepository_Decorated@673919a7]
resources: org.gradle.api.internal.resources.DefaultResourceHandler@25d93198
rootDir: /Users/mac_wk/IdeaProjects/Test
rootProject: root project 'Test'
runtimeClasspath: file collection
scriptPluginFactory: org.gradle.configuration.DefaultScriptPluginFactory@2436ea2f
serviceRegistryFactory: org.gradle.internal.service.scopes.ProjectScopeServices$5@f951a7f
services: ProjectScopeServices
sourceCompatibility: 1.5   
sourceSets: [source set 'main', source set 'test']
sources: [source set 'main', source set 'test']
standardOutputCapture: org.gradle.logging.internal.DefaultLoggingManager@5292ceca
state: project state 'EXECUTED'
status: integration        
subprojects: []            
targetCompatibility: 1.5   
tasks: [task ':assemble', task ':build', task ':buildDependents', task ':buildNeeded', task ':check', task ':classes', task ':clean', task ':compileJava', task ':compileTestJava', task ':jar', task ':javadoc', task ':processResources', task ':processTestResources', task ':test', task ':testClasses']
test: task ':test'         
testClasses: task ':testClasses'
testReportDir: /Users/mac_wk/IdeaProjects/Test/build/reports/tests
testReportDirName: tests   
testResultsDir: /Users/mac_wk/IdeaProjects/Test/build/test-results
testResultsDirName: test-results
version: 1.0         

大概的看一下就能够知道大概做了什么任务了,为什么会自动创建build文件夹,因为他默认执行了创建文件的命令,而上面的属性定义了这些任务描述或者属性,我们可以试试,比如咱们执行一下下面的这个脚本你就会发觉默认的build并没有自己生成而是变成了自定义的地方 采用命令gradle build

apply plugin: 'java'

sourceCompatibility = 1.5
version = '1.0'
buildDir = "/Users/mac_wk/IdeaProjects/Test/build_one"
repositories 
    mavenCentral()


dependencies 
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'org.springframework:spring-context:4.1.1.RELEASE'

jar
    manifest
        attributes "title": "gradle start",
                    "version":version
    


命令三:发布jar的命令

可以通过这样的配置,把jar 包发布到本地或者是远程,或者多个目录下 对下面的脚本执行gradle uploadArchives

uploadArchives
        
            repositories
                flatDir
                    dirs 'repos1'
                
            
        





以上是关于gradle 教程学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

Gradle笔记——构建基础

Gradle学习笔记--Gradle项目

Gradle学习笔记

Gradle学习笔记

Gradle学习笔记之Groovy

HTTP——学习笔记