Packaging Spring to a jar or war

This is going to be a boring post, the flip side is that is short. I am working with Spring STS and Maven, I have already written a simple Hello World web service for Spring using Boot, and letting it use the default built-in Tomcat application server.

Let's spend some words on how to actually create the fat jar that could be run from the shell, automagically running the embedded Tomcat and the web services in it, and then how to generate instead a plain old war that could be deployed in a stand alone Tomcat.

Fat jar

The first alternative could be achieved in a click, run the Maven install goal for the project. I can either run it from the project root or, as showed below, from its pom.xml element.

The first time I ran it, I saw an annoying warning message in the log:
[WARNING] The requested profile "pom.xml" 
 could not be activated because it does not exist.
To get rid of it, I removed a spurious Maven profile from the project properties

Warning or not, Maven does its job, and I see a jar generated in the target folder, that I can run from the command line. Something like this:
...\helloSpring\target>java -jar hello-0.0.1-SNAPSHOT.jar

Classic war
If I want to get a plain old war to be deployed on an already existing application server, a few changes are required.

Java code changes

My HelloSpringApplication class should extend SpringBootServletInitializer and should override the configure method. Pay attention to the super class package, the old one, in the context.web package is now deprecated for the new one.
package dd.manny.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

public class HelloSpringApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {, args);

    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(HelloSpringApplication.class);

Configuration changes

In the POM file, the packaging element under project is now set to war, and not anymore as jar:
Then, a new dependency should be added:
And the spring-boot-maven-plugin plugin removed.

After these changes, when I run pom.xml as Maven install, I generate a war, slimmer than the original jar, that now I can deploy to my Tomcat server.

No comments:

Post a Comment