注意点
spring boot项目构建为jar包或war包均可,如果构建为jar包,在构建时指定MainClass。如果构建为war包,在代码中不能以main方法所在类作为启动类,而以下面的代码所谓启动类。
@SpringBootApplication
public class WebStart extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebStart.class);
}
}
在开发过程中,可以定义main方法类继承该类,从而通过main方法启动项目,节约时间。
import org.springframework.boot.SpringApplication;
public class RunMain extends WebStart {
public static void main(String[] args) {
new SpringApplication(WebStart.class).run(args);
}
}
进入主题
构建jar文件,以spring boot内置容器运行
build.gradle配置
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gradle-simple'
version = '0.1.0'
manifest {
attributes 'Main-Class': 'com.sam.demo.RunMain'
}
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("junit:junit")
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
构建项目,生成jar文件
E:\workspace2\gradle-simple>gradle clean build
:clean
:compileJava
:processResources
:classes
:findMainClass
:jar
:bootRepackage
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build
BUILD SUCCESSFUL
Total time: 6.801 secs
运行jar文件
E:\workspace2\gradle-simple>cd build
E:\workspace2\gradle-simple\build>cd libs
E:\workspace2\gradle-simple\build\libs>java -jar gradle-simple-0.1.0.jar
构建war文件,部署至外部容器(tomcat)
build.gradle配置
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
}
}
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
war {
baseName = "gradle-simple"
extension = "zip"
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("junit:junit")
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
构建项目,生成zip文件
E:\workspace2\gradle-simple>gradle clean war
:clean
:compileJava
:processResources
:classes
:war
BUILD SUCCESSFUL
Total time: 7.295 secs
生成的zip文件名为gradle-simple.zip
解压zip文件至外部容器相应目录即可。
附
如果需要构建war文件,则将
extension = "zip"
从build.gradle配置文件中的war插件配置部分删除。即将war { baseName = "gradle-simple" extension = "zip" }
改为
war { baseName = "gradle-simple" }
即可。生成的war文件名为gradle-simple.war
网友评论