skip to Main Content

I need to send a JSON file to API that receives it and processes further. The main issue I’m having is initializing that POST method at application startup. I’ve created the JSON files, so only that is left over is to activate POST method when the application starts.
I know this is for demonstrating purposes but still haven’t found anything like that in Springs documentation.

Basically when the SpringBoot application is run, the first thing that it does is call a post method and sends those JSON files to API. Any ideas?

2

Answers


  1. You can use ApplicationReadyEvent listener. Whenever the application will start it will execute one time. Make sure the record / class should be a component.

    @Component
    public record AppStartupRunner() {
        @EventListener(ApplicationReadyEvent.class)
        public void init() throws IOException {
           // call your post method here
        }
    }
    
    Login or Signup to reply.
  2. You can do this in a couple of ways:

    • Use an EventListner Handler (this is what I prefer)
    • Create a Configuration with a @PostConstruct which has the logic – this is something I don’t prefer cause it might not always be the one to run post-startup, and in this case, we need RestTemplate so we need to think of Order of our configuration class, which I think we should tend to avoid as much as possible.

    For EventListener, you can have the below Component which executes on the ApplicationStartedEvent.

    @Component
    public class AppStartupEventHandler {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(AppStartupEventHandler.class);
    
        @EventListener
        public void onApplicationStartUp(ApplicationStartedEvent event) {
            // Have your start business here - or better delegate
            LOGGER.info("This is triggered post startup");
        }
    
    }
    

    More details can be found here in the official docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search