如何手动初始化项目目录结构,并在命令行用gradle编译运行项目

父目录 Android 开发入门 - wuyujin1997

Intro

常规来讲,在公司内开发都会用到IDE(集成开发环境),不过就是把一些命令行操作,一些需要手动执行的操作集成到界面上。你点一下按钮,一连串动作就在后台自动执行了,方便快捷且降低了手动操作的出错率。

不过万变不离其宗,相关工具的命令行基本用法还是需要熟悉一下。

以下内容分两部分:

  1. 啥也没有,完全从头开始初始化项目;
  2. 项目结构已存在(主要是项目目录中已经有了 build.gradle);

纯手动

大致步骤如下(参考 https://spring.io/guides/gs/gradle/ ):

  1. 手动创建项目目录结构+基本的源码文件;
  2. 使用 gradle wrapper 生成 gradle-wrapper 目录及gradlew脚本;
  3. 使用生成的 gradlew 脚本执行gradle操作。

手动创建项目目录结构+源码

mkdir -p src/main/java/hello

wuyujin1997@mac11 gradle-wrapper-show % pwd
/Users/wuyujin1997/Coderepo/gradle-wrapper-show
wuyujin1997@mac11 gradle-wrapper-show % ls
wuyujin1997@mac11 gradle-wrapper-show % mkdir -p src/main/java/hello
wuyujin1997@mac11 gradle-wrapper-show % tree
.
└── src
    └── main
        └── java
            └── hello

4 directories, 0 files
wuyujin1997@mac11 gradle-wrapper-show % 

接下来新增一个主类和一个空的build.gradle文件:
在这里插入图片描述
主类代码:

package hello;

public class HelloWorld {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("Hello 世界");
    }
}

gradle tasks

因为这个时候 build.gradle 配置文件是空的,所以执行 gradle tasks 可以看到最基本的几个task:

wuyujin1997@mac11 gradle-wrapper-show % gradle tasks

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'gradle-wrapper-show'
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'gradle-wrapper-show'.
dependencies - Displays all dependencies declared in root project 'gradle-wrapper-show'.
dependencyInsight - Displays the insight into a specific dependency in root project 'gradle-wrapper-show'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'gradle-wrapper-show'.
projects - Displays the sub-projects of root project 'gradle-wrapper-show'.
properties - Displays the properties of root project 'gradle-wrapper-show'.
resolvableConfigurations - Displays the configurations that can be resolved in root project 'gradle-wrapper-show'.
tasks - Displays the tasks runnable from root project 'gradle-wrapper-show'.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed
wuyujin1997@mac11 gradle-wrapper-show %

gradle wrapper

这个命令用于生成一些东西。详情见后,在执行命令后多出了什么,就是生成了什么。
gradle wrapper --gradle-version 6.0.1

执行前:

在这里插入图片描述

执行后:

在这里插入图片描述

执行前后对比:

wuyujin1997@mac11 gradle-wrapper-show % tree
.
├── build.gradle
└── src
    └── main
        └── java
            └── hello
                └── HelloWorld.java

4 directories, 2 files
wuyujin1997@mac11 gradle-wrapper-show % 
wuyujin1997@mac11 gradle-wrapper-show % gradle wrapper

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
wuyujin1997@mac11 gradle-wrapper-show % 
wuyujin1997@mac11 gradle-wrapper-show % tree          
.
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── src
    └── main
        └── java
            └── hello
                └── HelloWorld.java

6 directories, 6 files
wuyujin1997@mac11 gradle-wrapper-show % 

多出了什么?

├── gradle		# gradle wrapper 目录
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties	# 主要是配置项目要用到的 【gradle 的版本及下载链接】。
├── gradlew			# 类unix环境下的脚本
├── gradlew.bat	# windows环境下的脚本

gradle wrapper

先说这玩意是干嘛的,即它为何而存在?

不同的人在初始化同一个项目的时候,有可能会因为编译工具的版本不一致导致编译错误。
那么有没有办法让大家使用同一个版本的编译工具呢?有的。
在项目代码库中的某个位置,指定项目要使用的编译工具的版本和下载链接,即gradle-wrapper.properties

其实也有另一个原因,为了让有些人不用在本地系统下载配置gradle也能成功编译本项目(用的是本项目中配置好的gradle)。
来瞄一眼这个配置文件:

在这里插入图片描述其中最重要的一个配置项就是 distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip

gradlew 和 gradlew.bat

项目目录下执行这两个脚本 ./gradlew ./gradlew.bat 和直接执行配置于环境变量path的 gradle 有何区别?
不是同一个gradle。
执行这两个脚本,会间接调用到在 ./gradle/wrapper/gradle-wrapper.properties 中配置的gradle版本。

plugin java

修改build.gradleapply plugin: 'java'
在这里插入图片描述

再次查看有哪些 task:

wuyujin1997@mac11 gradle-wrapper-show % ./gradlew tasks

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'gradle-wrapper-show'
------------------------------------------------------------

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'gradle-wrapper-show'.
dependencies - Displays all dependencies declared in root project 'gradle-wrapper-show'.
dependencyInsight - Displays the insight into a specific dependency in root project 'gradle-wrapper-show'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'gradle-wrapper-show'.
projects - Displays the sub-projects of root project 'gradle-wrapper-show'.
properties - Displays the properties of root project 'gradle-wrapper-show'.
resolvableConfigurations - Displays the configurations that can be resolved in root project 'gradle-wrapper-show'.
tasks - Displays the tasks runnable from root project 'gradle-wrapper-show'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.

Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.

To see all tasks and more detail, run gradlew tasks --all

To see more detail about a task, run gradlew help --task <task>

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed
wuyujin1997@mac11 gradle-wrapper-show %

编译Java项目

./gradlew clean
./gradlew build
./gradlew run

在这里插入图片描述但是此时执行 gradle run 会报错:

wuyujin1997@mac11 gradle-wrapper-show % ./gradlew run  

FAILURE: Build failed with an exception.

* What went wrong:
Task 'run' not found in root project 'gradle-wrapper-show'.

* Try:
> Run gradlew tasks to get a list of available tasks.
> For more on name expansion, please refer to https://docs.gradle.org/8.2/userguide/command_line_interface.html#sec:name_abbreviation in the Gradle documentation.
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.

BUILD FAILED in 1s
wuyujin1997@mac11 gradle-wrapper-show % 

【重点】如何通过 gradle run 运行编译的生成物jar包?

build.gradle 添加配置:

apply plugin: 'application'

mainClassName = 'hello.HelloWorld'

然后重新 clean, build, run 即可执行jar包:

wuyujin1997@mac11 gradle-wrapper-show % ./gradlew run

> Task :run
Hello 世界

Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

For more on this, please refer to https://docs.gradle.org/8.2/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.

BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
wuyujin1997@mac11 gradle-wrapper-show % 

【重点】如何新增依赖

修改build.gradle中的配置,然后在java代码中调用类库文件测试一下:
在这里插入图片描述
build.gradle:

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'hello.HelloWorld'

repositories {
    
     
    mavenCentral() 
}

dependencies {
    
    
    implementation "joda-time:joda-time:2.2"
    testImplementation "junit:junit:4.12"
}

HelloWorld.java

package hello;

public class HelloWorld {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("依赖库:time = " + new org.joda.time.LocalTime());
        System.out.println(org.joda.time.LocalTime.class.getName());
        System.out.println("Hello 世界");
    }
}

在这里插入图片描述

更多关于 build.gradle 的配置项

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'

mainClassName = 'hello.HelloWorld'

// tag::repositories[]
repositories {
    
     
    mavenCentral() 
}
// end::repositories[]

// tag::jar[]
jar {
    
    
    archiveBaseName = 'gs-gradle'
    archiveVersion =  '0.1.0'
}
// end::jar[]

// tag::dependencies[]
sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    
    
    implementation "joda-time:joda-time:2.2"
    testImplementation "junit:junit:4.12"
}
// end::dependencies[]

// tag::wrapper[]
// end::wrapper[]

如何全程使用我们配置在环境变量中的gradle去处理项目?

命令列表

pwd
mkdir gradle-test
cd gradle-test 
pwd        
gradle init		# 初始化一个项目结构,以及最重要的 build.gradle 配置文件。
pwd   
ls
tree
gradle help
gradle tasks		# 列出有哪些可以执行的 task
gradle clean		# 清除项目的编译生成物(一般为 build/ 目录)
gradle build		# 编译项目
gradle run			# 执行编译的生成物(本task不一定存在,取决于 build.gradle 中配置了哪些 plugin)

要注意的是,在这一些列操作中,gradle相关的操作都是用的哪个Gradle?
用的是我配置在环境变量中的gradle。

命令执行细节


# 打印当前目录
wuyujin1997@mac11 Coderepo % pwd
/Users/wuyujin1997/Coderepo

# 创建一个新目录
wuyujin1997@mac11 Coderepo % mkdir gradle-test

# 进入刚才创建的新目录
wuyujin1997@mac11 Coderepo % cd gradle-test 

# 再次打印当前目录
wuyujin1997@mac11 gradle-test % pwd        
/Users/wuyujin1997/Coderepo/gradle-test

# 【使用 gradle命令 初始化一个基于 gradle 来管理依赖和编译流程的项目基本结构】
wuyujin1997@mac11 gradle-test % gradle init

Select type of project to generate:
  1: basic
  2: application
  3: library
  4: Gradle plugin
Enter selection (default: basic) [1..4] 2

Select implementation language:
  1: C++
  2: Groovy
  3: Java
  4: Kotlin
  5: Scala
  6: Swift
Enter selection (default: Java) [1..6] 3

Generate multiple subprojects for application? (default: no) [yes, no] no
Select build script DSL:
  1: Kotlin
  2: Groovy
Enter selection (default: Kotlin) [1..2] 1

Select test framework:
  1: JUnit 4
  2: TestNG
  3: Spock
  4: JUnit Jupiter
Enter selection (default: JUnit Jupiter) [1..4] 1

Project name (default: gradle-test): 
Source package (default: gradle.test): 
Enter target version of Java (min. 7) (default: 11): 11
Generate build using new APIs and behavior (some features may change in the next minor releas

> Task :init
To learn more about Gradle by exploring our Samples at https://docs.gradle.org/8.2/samples/sample_building_java_applications.html

BUILD SUCCESSFUL in 1m 14s
2 actionable tasks: 2 executed

# 再次打印当前目录
wuyujin1997@mac11 gradle-test % pwd   
/Users/wuyujin1997/Coderepo/gradle-test

# 列出当前目录下的文件列表
wuyujin1997@mac11 gradle-test % ls
app			gradlew			settings.gradle.kts
gradle			gradlew.bat

# 树型打印当前目录下的文件夹层级/文件列表
wuyujin1997@mac11 gradle-test % tree
.
├── app
│   ├── build.gradle.kts
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── gradle
│       │   │       └── test
│       │   │           └── App.java
│       │   └── resources
│       └── test
│           ├── java
│           │   └── gradle
│           │       └── test
│           │           └── AppTest.java
│           └── resources
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle.kts

14 directories, 8 files

# 【gradle的帮助信息】
wuyujin1997@mac11 gradle-test % gradle help
<-------------> 0% INITIALIZING [54s]
Unable to locate local Maven repository.

> Task :help

Welcome to Gradle 8.2.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see more detail about a task, run gradle help --task <task>

To see a list of command-line options, run gradle --help

For more detail on using Gradle, see https://docs.gradle.org/8.2/userguide/command_line_interface.html

For troubleshooting, visit https://help.gradle.org

BUILD SUCCESSFUL in 1m 14s
1 actionable task: 1 executed

# 【基于当前的 build.gradle 配置文件,查看gradle可执行的任务有哪些?】
# 【重点: 具体有哪些task,其实取决于 build.gradle 中配置了哪些 plugin 。】
wuyujin1997@mac11 gradle-test % gradle tasks

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'gradle-test'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'gradle-test'.
dependencies - Displays all dependencies declared in root project 'gradle-test'.
dependencyInsight - Displays the insight into a specific dependency in root project 'gradle-test'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
kotlinDslAccessorsReport - Prints the Kotlin code for accessing the currently available project extensions and conventions.
outgoingVariants - Displays the outgoing variants of root project 'gradle-test'.
projects - Displays the sub-projects of root project 'gradle-test'.
properties - Displays the properties of root project 'gradle-test'.
resolvableConfigurations - Displays the configurations that can be resolved in root project 'gradle-test'.
tasks - Displays the tasks runnable from root project 'gradle-test' (some of the displayed tasks may belong to subprojects).

Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

# 清除项目中的编译痕迹(一般为 build/ 目录)
wuyujin1997@mac11 gradle-test % gradle clean

BUILD SUCCESSFUL in 1s
1 actionable task: 1 up-to-date

# 重新编译
wuyujin1997@mac11 gradle-test % gradle build

> Task :app:compileJava
Unable to locate local Maven repository.

BUILD SUCCESSFUL in 15s
7 actionable tasks: 7 executed

# 运行打包后的生成物【有没有这个tasks,完全取决于你的 build.gradle 中配置了哪些 plugin】
wuyujin1997@mac11 gradle-test % gradle run

> Task :app:run
Hello World!

BUILD SUCCESSFUL in 2s
2 actionable tasks: 1 executed, 1 up-to-date

# 
wuyujin1997@mac11 gradle-test % 

猜你喜欢

转载自blog.csdn.net/wuyujin1997/article/details/131756083
今日推荐