Spring Boot without the web server

if you want to run Spring Boot 1.x without a servlet container, but with one on the classpath (e.g. for tests), use the following, as described in the spring boot documentation:

@Configuration
@EnableAutoConfiguration
public class MyClass {
    public static void main(String[] args) throws JAXBException {
         SpringApplication app = new SpringApplication(MyClass.class);
         app.setWebEnvironment(false); //<<<<<<<<<
         ConfigurableApplicationContext ctx = app.run(args);
    }
}

also, I just stumbled across this property:

spring.main.web-environment=false

Spring Boot 2.x, 3.x

  • Application Properties

      spring.main.web-application-type=NONE 
      # REACTIVE, SERVLET
    
  • or SpringApplicationBuilder

      @SpringBootApplication
      public class MyApplication {
    
          public static void main(String[] args) {
              new SpringApplicationBuilder(MyApplication.class)
                  .web(WebApplicationType.NONE) // .REACTIVE, .SERVLET
                  .run(args);
         }
      }
    

Where WebApplicationType:

  • NONE - The application should not run as a web application and should not start an embedded web server.
  • REACTIVE - The application should run as a reactive web application and should start an embedded reactive web server.
  • SERVLET - The application should run as a servlet-based web application and should start an embedded servlet web server.

You can create something like this:

@SpringBootApplication
public class Application {
  public static void main(String[] args) {
    new SpringApplicationBuilder(Application.class).web(false).run(args);
  }
}

And

@Component
public class CommandLiner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {
    // Put your logic here
  }

}

The dependency is still there though but not used.