Gradle進階:1: 結合spring boot進行web開發

淼叔發表於2018-12-11

在這裡插入圖片描述
在前面的文章中介紹瞭如何使用gradle的基礎知識,這篇文章在某種程度上才是真正意義上的第一個hello world,這裡使用一個簡單的spring boot的例子,通過gradle進行編譯和構建以及確認。

事前準備

環境準備

元件/框架 版本
JDK 1.8.0
Gradle 4.10.2
Spring Boot 2.1.1
liumiaocn:springboot liumiao$ gradle -v

------------------------------------------------------------
Gradle 4.10.2
------------------------------------------------------------

Build time:   2018-09-19 18:10:15 UTC
Revision:     b4d8d5d170bb4ba516e88d7fe5647e2323d791dd

Kotlin DSL:   1.0-rc-6
Kotlin:       1.2.61
Groovy:       2.4.15
Ant:          Apache Ant(TM) version 1.9.11 compiled on March 23 2018
JVM:          1.8.0_191 (Oracle Corporation 25.191-b12)
OS:           Mac OS X 10.14 x86_64

liumiaocn:springboot liumiao$

spring boot demo應用

目錄結構

使用https://start.spring.io/或者自己手動建立如下結構的目錄結構

liumiaocn:springboot liumiao$ tree 
.
├── build.gradle
├── settings.gradle
└── src
    └── main
        ├── java
        │   └── com
        │       └── liumiaocn
        │           └── springbootdemo
        │               └── SpringbootdemoApplication.java
        └── resources
            └── application.properties

7 directories, 4 files
liumiaocn:springboot liumiao$

spring boot相關說明

詳細請參看spring boot相關說明,本文不再贅述:
https://blog.csdn.net/liumiaocn/article/details/83548217

liumiaocn:springboot liumiao$ cat src/main/resources/application.properties 
liumiaocn:springboot liumiao$ cat src/main/java/com/liumiaocn/springbootdemo/SpringbootdemoApplication.java 
package com.liumiaocn.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
@SpringBootApplication
public class SpringbootdemoApplication {
        @RequestMapping("/")
        String home() {
          return "Hello, Spring Boot 2";
        }

	public static void main(String[] args) {
		SpringApplication.run(SpringbootdemoApplication.class, args);
	}
}
liumiaocn:springboot liumiao$

gradle設定: settings.gradle

settings.gradle中僅設定rootProject.name資訊,用於作為預設的jar檔案的名稱等用處。

liumiaocn:springboot liumiao$ cat settings.gradle 
rootProject.name = 'springbootdemo'
liumiaocn:springboot liumiao$ 

gradle設定:build.gradle

build.gradle中做如下設定,簡單說明如下:

  • ext: 用於定義自定義屬性,屬性的多種使用方式在基礎篇進行過詳細介紹,這裡不再贅述
  • repositories:用於設定maven倉庫,這裡的例子使用了mavenCentral,如果使用其他的私庫,可使用maven{ url ‘http://xxx’}的方式替換即可
  • dependencies:比照spring boot的maven的寫法,可看到這裡spring-boot-gradle-plugin和spring-boot-starter-web的引入
  • GAV:maven座標,在gradle裡可以通過group和version進行直接設定
  • sourceCompatibility:用於設定java版本
  • apply plugin:引入了java/org.springframework.boot/io.spring.dependency-management
liumiaocn:springboot liumiao$ cat build.gradle 
buildscript {
	ext {
		springBootVersion = '2.1.1.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

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

repositories {
	mavenCentral()
}


dependencies {
	implementation('org.springframework.boot:spring-boot-starter-web')
}
liumiaocn:springboot liumiao$

可以通過gradle tasks檢視apply plugin所引入的task資訊

liumiaocn:springboot liumiao$ gradle tasks

> Task :tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Application tasks
-----------------
bootRun - Runs this project as a Spring Boot application.

Build tasks
-----------
assemble - Assembles the outputs of this project.
bootJar - Assembles an executable jar archive containing the main classes and their dependencies.
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 main classes.
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 source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'springbootdemo'.
components - Displays the components produced by root project 'springbootdemo'. [incubating]
dependencies - Displays all dependencies declared in root project 'springbootdemo'.
dependencyInsight - Displays the insight into a specific dependency in root project 'springbootdemo'.
dependencyManagement - Displays the dependency management declared in root project 'springbootdemo'.
dependentComponents - Displays the dependent components of components in root project 'springbootdemo'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'springbootdemo'. [incubating]
projects - Displays the sub-projects of root project 'springbootdemo'.
properties - Displays the properties of root project 'springbootdemo'.
tasks - Displays the tasks runnable from root project 'springbootdemo'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.

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

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 0s
1 actionable task: 1 executed
liumiaocn:springboot liumiao$

構建

通過使用gradle build或者bootJar進行構建

liumiaocn:springboot liumiao$ ls
build.gradle    settings.gradle src
liumiaocn:springboot liumiao$ gradle build

BUILD SUCCESSFUL in 1s
3 actionable tasks: 3 executed
liumiaocn:springboot liumiao$ ls
build           build.gradle    settings.gradle src
liumiaocn:springboot liumiao$ 

可以看到,gradle build生成了一個build的目錄,此構建結果目錄詳細資訊如下:

liumiaocn:springboot liumiao$ tree build
build
├── classes
│   └── java
│       └── main
│           └── com
│               └── liumiaocn
│                   └── springbootdemo
│                       └── SpringbootdemoApplication.class
├── libs
│   └── springbootdemo-0.0.1-SNAPSHOT.jar
├── resources
│   └── main
│       └── application.properties
└── tmp
    ├── bootJar
    │   └── MANIFEST.MF
    └── compileJava

12 directories, 4 files
liumiaocn:springboot liumiao$

結果確認

啟動spring boot應用

使用java -jar 啟動生成的springboot的jar檔案,也可以使用外掛封裝的bootRun任務來執行,這裡使用gradle bootRun來執行

liumiaocn:springboot liumiao$ gradle bootRun

> Task :bootRun

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.1.RELEASE)

2018-12-11 07:24:42.354  INFO 49488 --- [           main] c.l.s.SpringbootdemoApplication          : Starting SpringbootdemoApplication on liumiaocn with PID 49488 (/Users/liumiao/gradle/springboot/build/classes/java/main started by liumiao in /Users/liumiao/gradle/springboot)
2018-12-11 07:24:42.362  INFO 49488 --- [           main] c.l.s.SpringbootdemoApplication          : No active profile set, falling back to default profiles: default
2018-12-11 07:24:44.593  INFO 49488 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-12-11 07:24:44.649  INFO 49488 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-12-11 07:24:44.649  INFO 49488 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.13
2018-12-11 07:24:44.674  INFO 49488 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/liumiao/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-12-11 07:24:44.876  INFO 49488 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-12-11 07:24:44.876  INFO 49488 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2420 ms
2018-12-11 07:24:45.398  INFO 49488 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2018-12-11 07:24:45.869  INFO 49488 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-12-11 07:24:45.876  INFO 49488 --- [           main] c.l.s.SpringbootdemoApplication          : Started SpringbootdemoApplication in 4.26 seconds (JVM running for 5.059)
<=========----> 75% EXECUTING [17s]
> :bootRun

確認結果

可以通過頁面訪問確認應用資訊
在這裡插入圖片描述
也可以通過curl來確認

liumiaocn:~ liumiao$ curl http://localhost:8080/
Hello, Spring Boot 2liumiaocn:~ liumiao$

其他章節

總結

通過使用spring boot和java的相關外掛,可以很容易地使用gradle來進行spring boot的web專案的構建,在下篇文章中將結合Junit的實施方式進行示例說明。

相關文章