I need to run my Spring Boot app in two modes:
- As command line application (without Tomcat) as
CommandLineRunner
- As
SpringBootServletInitializer
REST API app for standalone Tomcat.
Question: Is it possible? How can I achieve this setup?
I need to run my Spring Boot app in two modes:
CommandLineRunner
SpringBootServletInitializer
REST API app for standalone Tomcat.Question: Is it possible? How can I achieve this setup?
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:
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
Add @Profile("cmd")
on CommandLineRunner
implementation so that it would run only when profile 'cmd' is specified.
Run java -jar myapp.war
with --spring.profiles.active=cmd
flag so that cmd profile will be loaded.
Don't change anything for tomcat deployment - profile cmd won't be activated and CommandLineRunner won't run