Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot application war in a standalone servlet container

A general question about building a war from a spring boot application and running it in a standalone servlet container. The documentation I've seems seems at odds with examples on Stack Overflow.

The answer here shows the way I read of doing this a couple of months ago. I read this here, but the guide seems to have changed losing the actual example app.

Here the "configure" method references the main spring boot Application.class.

public class WebInitializer extends SpringBootServletInitializer {   

   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
    }  
}

There are also these posts here and here that show the "configure" method referring to the SpringBootServletInitializer sub class itself.

public class BootStrap extends SpringBootServletInitializer {

   public static void main(String[] args) {
      SpringApplication.run(BootStrap.class, args);
   }

   @Override
   protected SpringApplicationBuilder configure(
          SpringApplicationBuilder application) {
      return application.sources(BootStrap.class);
   }   
}

and also there is a main method.

Also the spring-boot-sample-traditional  example app at https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples, which shows "WAR packaging" does it differently

 public class WebConfig extends WebMvcConfigurerAdapter {.........

I was wondering is there are issues with choosing over these different ways of seemingly achieving the same thing in spring boot? Or do they all work equally as well and are interchangeable?

like image 962
n99 Avatar asked Feb 11 '15 19:02

n99


1 Answers

Having your main application class extend SpringBootServletInitializer (Bootstrap in your question) or using a separate class (WebInitializer in your question) is down to personal taste. My preference is to take the Bootstrap approach but they both work in the same way; pick which ever you prefer.

If you are only going to deploy your application to a standalone servlet container then you don't need a main method. The main method is used if you want to run the application as an executable war (java -jar my-app.war), or you want to be able to run it directly in your IDE, i.e. without having your IDE deploy it to a servlet container.

spring-boot-sample-traditional illustrates the use of web.xml to Bootstrap a Spring Boot application. Generally speaking, this isn't a recommended approach unless you're stuck on a Servlet 2.5 container. The use of WebMvcConfigurerAdapter has nothing to do with WAR packaging. Take a look at its web.xml to see the relevant pieces of configuration.

like image 60
Andy Wilkinson Avatar answered Oct 14 '22 07:10

Andy Wilkinson