Search code examples
javaspringspring-bootspring-ioc

What's the best way to Invoke a service on spring-boot start up?


I have a spring boot application and i need to invoke a service(a rest end point)on start up.


Solution

  • CommandLineRunner

    @Component
    public class MyBean implements CommandLineRunner {
    
        public void run(String... args) {
            // Do something...
        }
    
    }
    

    You can perform any task you'd like at Application startup with this handy interface.

    To call a REST endpoint you can use RestTemplate

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject("http://www.example.com/api/resource", String.class);
    

    If you build a POJO with fields that match the JSON response, the RestTemplate will automatically map them with the help of Jackson. See the docs for more detail.