Spring Boot is a great framework for web applications, but when it comes to writing console applications it is not that straightforward as for web.
For example you want, as I needed to, to import data from some data source like CSV file. Creating web endpoint for that might be not that practical from standpoint of polluting REST API as well as security concerns. Thus CLI application is a good choice here.
It is also a must to have the Spring context by side to follow the DRY principle by re-using persistence models. So whenever models are changed, we make sure import functionality stays intact, due to importing logic will also be affected and visible in most cases on compiler level, on top of that this safety net can easily be enhanced with unit or integration tests. In addition it should function alongside with web application code.
Following solution do not require any external dependencies:
Run only under defined profile and disable web application
Add property to disable web application under “import” profile to src/main/resources/application-import.properties
After that running under “import” profile will disable web part and run only console part.
Debug & run under IntelliJ IDEA
Copy existing DemoApplication, rename as you want and add “import” profile
Just hit the “Debug” icon:
Run under Maven
Normally we run spring boot application using Spring Boot Maven Plugin like this
To run our console application we have to run it with “import” profile active (-q switch is here to suppress compiler output):
mvn -q spring-boot:run -Dspring-boot.run.jvmArguments="-Dspring.profiles.active=import"
Passing the arguments
Under IntelliJ IDEA is quite easy, in run configuration, we’ve configured in previous step, just unfold “Environment” tab and add the arguments:
Which results in:
Under Maven a bit more tricky, since arguments are not fed directly to application, we have to workaround it with passing arguments through spring-boot.run.arguments variable:
mvn -q spring-boot:run -Dspring-boot.run.jvmArguments="-Dspring.profiles.active=import" -Dspring-boot.run.arguments="a b c"
We can use wrapper shell script to convert regular arguments to spring-boot.run.arguments variable to run import job in more convenient way:
So we can run simply
./import.sh a b c
Running in packaged JAR
More straightforward since arguments are passed directly:
java -Dspring.profiles.active=import -jar target/demo-0.0.1-SNAPSHOT.jar a b c