Search code examples
spring-bootpid

how to get process id of a spring boot application


I noticed spring boot printed the process id in the log during it's startup. Now I want write a script to kill this process using this pid and start the application again. Does Spring Boot provide any api to get this pid? Thanks!


Solution

  • Spring Boot provides the class ApplicationPidFileWriter, which will then write the PID into a file. You can activate it by adding it as a listener to the SpringApplication:

    SpringApplication springApplication = new SpringApplication(DemoApplication.class);
    springApplication.addListeners(new ApplicationPidFileWriter());
    springApplication.run(args);
    

    The constructor of ApplicationPidFileWriter can also take a String or a File object with a custom filename. Then you can read the PID from that file and use it in your scripts.