Spring Boot+Gradle项目打包发布

时间:2022-01-27 09:17:47

在Eclipse中创建Spring Boot项目有两种方法,

1. 创建一个单纯的Gradle项目,然后转换为Dynamic Web Module项目,添加SpringBoot的引用,如:

    http://blog.csdn.net/haojinming/article/details/79295255 中所示。

此时build.gradle文件如下:

/*
 * This build file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java Library project to get you started.
 * For more details take a look at the Java Libraries chapter in the Gradle
 * user guide available at https://docs.gradle.org/3.5/userguide/java_library_plugin.html
 */

// Apply the java-library plugin to add support for Java Library
apply plugin: 'java-library'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
    jcenter()
}

dependencies {

	// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
	compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.5.6.RELEASE'

    // Use JUnit test framework
    testImplementation 'junit:junit:4.12'
}

2. 在Eclipse Marketplace中安装Spring插件,可以直接创建一个Spring Boot项目,此时生成的buil.gradle文件如下:

buildscript {
	ext {
		springBootVersion = '1.5.10.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

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

repositories {
	mavenCentral()
}


dependencies {
	compile('org.springframework.boot:spring-boot-starter-web')
	testCompile('org.springframework.boot:spring-boot-starter-test')
	compile('com.microsoft.azure.sdk.iot:iot-service-client:1.11.0')
	compile('com.microsoft.azure.sdk.iot:iot-device-client:1.7.0')
}

第一种方法创建的项目不能直接打包成可运行的jar文件,可以替换成第二种方法下的build.gradle,就可以了,推荐直接用Spring插件创建项目。


打包方法: 在项目目录下运行

gradle tasks

看看Task列表中是否有bootRepackage,如果有,运行

gradle bootRepackage

在项目目录的build\libs中生成jar文件,通过java -jar XXX.jar就可以运行了。

Spring Boot+Gradle项目打包发布