karthik muthyam
karthik muthyam

Reputation: 121

call another service after sending the success response in spring boot?

The first controller is sending the success response after that it will call another method after sending the response.

I need to call m1()method after return the response

    @RequestMapping(value = {"/hello"}, method = POST, produces = { "application/json" })
        public Response getAllData(@RequestBody String request){

            return new ResponseEntity<>("Hello World");
        }

    public void m1(){

    }

Upvotes: 5

Views: 7888

Answers (5)

Yury Demidenko
Yury Demidenko

Reputation: 21

The most simple and reliable way - run a thread. Try-final isn't good at all. But the best solution is - throw out that SB and use pure JEE servlets to invoke all that you need (JSON, JPA, BM transactions) in the client's request's thread, so you will never get stuck like that.

Upvotes: 0

Shakirov Ramil
Shakirov Ramil

Reputation: 1543

you can use eventListener for creating event. And catch it in public method with EventListener annotation. https://www.baeldung.com/spring-events

Upvotes: 0

Jaganath Kamble
Jaganath Kamble

Reputation: 556

You need to add @EnableAsync in your configuration class or main class then create another service class encapsulating an Async method m1

In your class add the statement below:

asyncServiceImpl.m1();

@Service 
public class AsyncServiceImpl {

   @Async
   public CompletableFuture<String> m1() {
        // Your logic here
        return CompletableFuture.completedFuture(String.valueOf(Boolean.FALSE));
   }
}

Upvotes: 1

Ashish Bakwad
Ashish Bakwad

Reputation: 811

Example for the Spring AspectJ using @AfterReturning advice

@Aspect
@Component
public class A {

  /*
   * AfterReturning advice
   */
  @AfterReturning("execution(* com.package.ClassName.getAllData(..))")
  public void m1(JoinPoint joinPoint) {


  }
}

Upvotes: 4

Codewrapper
Codewrapper

Reputation: 430

The simple trick is to use try...finally.

try{
  return new Response();
} finally {
  //do after actions
}

'finally' will always execute after the try block no matter there is a return statement in it.

Upvotes: 4

Related Questions