I am currently working on a Spring application that when triggered, will send a POST request to an API endpoint. I am using Spring framework 5, with Rest Template used to create and execute the POST request. Currently I am saving the token locally in a file (along with it's issue time) and check it every time the application is triggered. The token has a lifetime of 2 hours, but I am currently refreshing the token every time the application is triggered or if the application is triggered in less than 1 hour since the last token issue. Otherwise, I would request for a new token. Is there any way to use RestTemplate (or other Spring framework library) to automatically refresh the token when it is going to be expired?
You can use scheduling in Spring to update it on regular interval (with cron jobs for example). Look at @Scheduled(cron = '')
. Also for your token, is there an special reason to keep it in file. Why not use a bean to store it and pass it around with @Autowired
?