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?
>Solution :
You can do this in a couple of ways:
- Use an
EventListnerHandler (this is what I prefer) - Create a
Configurationwith a@PostConstructwhich 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 needRestTemplateso we need to think ofOrderof 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