Running Scripts in a Sprint Boot Web Application
<p>I have a Spring Boot web application packaged as a WAR file and I wish to have the ability to run some tasks (scripts or commands) on-demand. For example:</p>

<ul>
<li>Initialize the database schema</li>
<li>Seed the database <strong>programmatically</strong></li>
<li>Data migration when required for new versions of the application (move files, database operations, etc.)</li>
<li>Validate data integrity between stored files and database contents</li>
</ul>

<p>These "commands" would be much easier to implement if they had access to the same beans (services, DAOs) and models as the web app proper. I expect I have to create a Spring application context somewhere for this to happen. I would also prefer to package these commands with the rest of the application so they are tested alongside it and easy to deploy.</p>

<p>Essentially, I want to know how to achieve something similar to <a href="https://laravel.com/docs/4.2/commands" rel="nofollow noreferrer">Laravel's artisan commands</a> (PHP).</p>

<p>I have read on running a class inside a WAR <a href="https://stackoverflow.com/questions/1842972/how-do-i-run-a-class-in-a-war-from-the-command-line">here</a> and <a href="https://stackoverflow.com/questions/6087876/how-to-run-java-class-file-inside-the-war-file">here</a>. I'm searching for the "Spring way" of packaging and running commands. Do I have to integrate <a href="http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-batch-applications" rel="nofollow noreferrer">Spring Batch jobs</a> for this? From what I understand, Spring Batch is meant for larger workloads which can be split in multiple batches. Should I bite the bullet and put the commands in a second separate maven module which references the first one?</p>

<h3>update</h3>

<p>I implemented an <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-spring-application.html#boot-features-command-line-runner" rel="nofollow noreferrer"><code>ApplicationRunner</code></a> (thanks Stefan!) to see how they work and found that they run after the Spring application context is refreshed. This means that the whole web application is initialized and active before the runner executes. This includes MVC endpoint mappers and scheduled tasks defined in configurations. While this can definitely be useful, I need to run commands when all that is not active because it can come in conflict with the commands (especially with transient data states during command runs).</p>

<h3>update 2</h3>

<p>I simply needed to create another executable jar that creates a Spring Boot application using a <code>CommandLineRunner</code>. This can reference all the beans from the web application if I use 3 modules:</p>

<ol>
<li>The spring "service" beans module</li>
<li>The web application module</li>
<li>The command line runner module</li>
</ol>