Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call another method after Spring MVC handler returns

I have a requirement where I need to return some status/Long value from a rest controller and then execute code to send push notification.

@RequestMapping(value="/create")
public String createTicket() throws InterruptedException {
    // code to create ticket
    return "ticket created";
    // need to call sendPushNotifiction() after I return status
}

    public void sendPushNotifiction() throws InterruptedException {
    // code to send push notification
    System.out.println("Sent push notification successfully!!");    
}

Can some one please tell me how to achieve this? Is it possible to use Spring AOP for this? I don't think thread will guaranteed execution of sendPushNotifiction method only after return. So what are the ways to achieve this effectively? Thanks in advance

like image 664
Pratap A.K Avatar asked Oct 17 '15 07:10

Pratap A.K


2 Answers

I think it might be a good use case for asynchronous processing. Spring has good support for it. Precisely, you need to

  1. Annotate sendPushNotifiction with @Async.
  2. Annotate some configuration class with @EnableAsync.
  3. Call sendPushNotifiction() before the return statement. The execution flow will not wait for sendPushNotifiction to finish.

If it doesn't work, try coding sendPushNotifiction in a separate service.

like image 105
Sanjay Avatar answered Oct 16 '22 15:10

Sanjay


Create another method which first calls the createTicket() method and then calls the sendPushNotifiction(). That will do the job. This the simplest way in my humble opinion.

like image 38
YoungHobbit Avatar answered Oct 16 '22 16:10

YoungHobbit