javalinuxbashspring-boot

Passing commands to a running app from command-line


I have a Java-app (Spring Boot) that is running permanently.

I need to pass arguments and commands to it - not directly at startup but during lifetime.

E.g. empty logs or reopen database

I like to do this from a Linux commandline.

What are some of the ways this can be achieved?

I can think of having a web-handler and using console web-clients (e.g. curl) or using files that the app reads in.


Solution

  • You can use Spring Shell for this in Spring Boot

    First, add the Spring Shell Dependency

    <dependency>
    <groupId>org.springframework.shell</groupId>
    <artifactId>spring-shell-starter</artifactId>
    </dependency>
    

    Then, add enable the interactive shell in your applicaion.properties

    spring.shell.interactive.enabled=true
    

    or, for yaml:

    spring:
      shell:
        interactive:
          enabled: true
    

    Then, you can write you first command like so:

        @ShellComponent
        public class MyCommands {
    
            @ShellMethod(key = "hello-world")
            public String helloWorld(
                @ShellOption(defaultValue = "spring") String arg
            ) {
                return "Hello world " + arg;
            }
        }
    

    When you run your spring boot application now, you can type help in the interactive shell and your command will be shown like this:

    My Commands
           hello-world:
    

    Finally, you can invoke it by typing the name of the command into the interactive shell:

    shell:>hello-world
    Hello world spring
    
    shell:>hello-world --arg boot
    Hello world boot