Calling Spring Boot method from terminal

2.1k Views Asked by At

I am researching how to call a method from the terminal.

@Component
public class ApplicationAdapter implements CommandLineRunner {

    @Autowired
    private IApplicationPort iApplicationPort;

    @Override
    public void run(String... args) throws Exception {
        iApplicationPort.getAll();
        iApplicationPort.deleteStudentById((long) 1);
    }
}

This is the main class

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        new ApplicationAdapter();
    }
}

I wish to call the 2 methods: getAll(); and deleteStudentById((long) 1); from the terminal. How can I do that?

1

There are 1 best solutions below

4
On

First you don't need to instantiate the ApplicationAdapter. This will be done by Spring because of the @Component annotation:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        // new ApplicationAdapter(); REMOVE
    }
}

Then you could use parameters that you pass when staring the application:

@Component
public class ApplicationAdapter implements CommandLineRunner {

    @Autowired
    private IApplicationPort iApplicationPort;

    @Override
    public void run(String... args) throws Exception {
        if (args[0].equals("all")) {
            iApplicationPort.getAll();
        } else if (args[0].equals("delete"))
            iApplicationPort.deleteStudentById(Long.parseLong(args[1]));
        } 
    }
}

Then you can start your app like:

java -jar yourApp.jar all

java -jar yourApp.jar delete 1