Spring Boot | Creating a WAR File
Creating a WAR File
Writing the Code
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE'
}
}
apply plugin: 'war'
apply plugin: 'spring-boot'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
providedCompile 'org.springframework.boot:spring-boot-starter-tomcat'
}
war {
baseName = 'spring-boot-war'
}
- Load the WAR plugin.
- Change the Tomcat dependency used as the embedded server to
providedCompile.
Main.java
package sample.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SpringBootApplication
public class Main extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Main.class);
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
- Define the
mainmethod and modify the class as shown above.- Extend
SpringBootServletInitializer. - Override
configure(SpringApplicationBuilder).
- Extend
SampleResource.java
package sample.springboot;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/sample")
public class SampleResource {
@RequestMapping(method=RequestMethod.GET)
public String hello() {
return "Hello Spring Boot!!";
}
}
- Resource class for testing.
Checking the Result
Build the WAR file.
$ gradle war
Deploy the generated spring-boot-war.jar under build/libs to Tomcat.
Check it with curl.
$ curl http://localhost:8080/spring-boot-war/sample
Hello Spring Boot!!
You can create a WAR file relatively easily.
References
- 59.4 Packaging executable jar and war files | Spring Boot Reference Guide
- 74.1 Create a deployable war file | Spring Boot Reference Guide
- Build a Spring Boot Application and Create a WAR File - M12i.