3

I need to run my Spring Boot app in two modes:

  1. As command line application (without Tomcat) as CommandLineRunner
  2. As SpringBootServletInitializer REST API app for standalone Tomcat.

Question: Is it possible? How can I achieve this setup?

jnemecz
  • 3,171
  • 8
  • 41
  • 77

1 Answers1

1

I think there is a contradiction in the question:

If you use SpringBootServletInitializer then the artifact is supposed to be packaged as WAR and deployed on some webserver like tomcat. Tomcat is not embedded in this case.

If you want an Embedded Tomcat, then you don't need WAR, you should use a "usual" jar type of spring boot application artifact.

A couple of facts that might help:

There is nothing special about CommandLineRunner beans except the fact spring boot automatically will run a run method on all beans that implement this interface when the application context becomes available.

The fact that you have a web starter in dependencies usually means that you intend to run the web server (tomcat), however its not always the case, you can specify the web env. type to 'NONE' and an embedded tomcat won't be started (see this thread for more technical information)

Now given these two facts, and assuming you don't really build a WAR (in this case you'll have to host it on embedded tomcat, java doesn't recognize WARs) - you can define a "flavour" - profile for example and define the configuration for command line runner to be active only for certain profile and the property of not-running the tomcat to be relevant for another type of profile.

Update

Based on OP's comment:

So, the goal is being able to run:

java -jar myapp.war

in a way that only CommandLineRunner will run and no real tomcat will be loaded

On the other hand you want to put myapp.war to webapps folder of some tomcat and in this way, CommandLineRunner won't be invoked, right?

In this case, consider implementing the following suggestion:

  1. create the application-cmd.properties and specify that the tomcat should not run (web env. type = NONE) - see the link that I've provided above

  2. Add @Profile("cmd") on CommandLineRunner implementation so that it would run only when profile 'cmd' is specified.

  3. Run java -jar myapp.war with --spring.profiles.active=cmd flag so that cmd profile will be loaded.

  4. Don't change anything for tomcat deployment - profile cmd won't be activated and CommandLineRunner won't run

Community
  • 1
  • 1
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
  • War is executable as same as jar. Not embeded, I use standalone Tomca, my fault. Please could you provide some piece of code or direct me to concrete documentation? – jnemecz Feb 05 '20 at 20:08