【业余开发笔记】用gradle构建一个简单的rest api

以下是一些gradle构建项目的使用笔记,由于自己对maven也算太了解,所以不谈区别和优劣了,就简单总结一下关于gradle的使用好了。

以下是关于用gradle构建一个以spring boot为框架很简单的一个restful web service
英文版介绍:http://spring.io/guides/gs/rest-service/
项目源码:https://github.com/spring-guides/gs-rest-service/archive/master.zip
关于gradle:http://www.gradle.org/

其实不用对这些构建工具有了解,自己粗略想想也大概知道,如果要自动构建一个java项目。
首先要有jdk,
构建工具需要知道java bin在哪里好编译和运行java代码
构建工具需要知道你的代码在哪里
构建工具需要知道你的外部依赖包在哪里
构建工具可能需要一个web服务器,可能在构建工具里,也可能需要下载

好了,大概知道这些,我们自己也可以动手写一个简单的自动化构建脚本了。
这里回归主题,看一个简单的gradle的配置文件
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.1.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-rest-service'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}


关于java在哪里,我们看到gradle的配置文件里指定了java的版本号
sourceCompatibility = 1.8
targetCompatibility = 1.8
source的版本和编译后的版本,于是大概不需要外部依赖包的就没问题了。

那在看看外部依赖包怎么来,
有个   
repositories {
   mavenCentral()
}
dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.1.RELEASE")
}

还有
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    testCompile("junit:junit")
}

初步的想想,大概就是从mavenCentral里把这些东西都下载下来吧。
而mavenCentral是https://repo1.maven.org/maven2

所以我们自己去到https://repo1.maven.org/maven2下,果不其然会发现
testCompile("junit:junit") => https://repo1.maven.org/maven2/junit/junit/
compile("org.springframework.boot:spring-boot-starter-web") => https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-starter-web/
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.1.RELEASE") =>https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-gradle-plugin/1.3.1.RELEASE/

而如何让自动构建工具发现我们自己写代码,就是他的gradle.build文件必须要和你的源代码有一个指定的关系,具体详见本文中提供的代码。

所以,所以,在有gradle.build的文件夹下运行一下gradle bootrun,一个简单的web service就构建好了。

猜你喜欢

转载自imnotokay.iteye.com/blog/2267010
今日推荐