简体   繁体   English

在 spring boot 中发送成功响应后调用另一个服务?

[英]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我需要在返回响应后调用 m1() 方法

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

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

    public void m1(){

    }

The simple trick is to use try...finally.简单的技巧是使用 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. 'finally' 将始终在 try 块之后执行,无论其中是否有 return 语句。

Example for the Spring AspectJ using @AfterReturning advice使用 @AfterReturning 建议的 Spring AspectJ 示例

@Aspect
@Component
public class A {

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


  }
}

You need to add @EnableAsync in your configuration class or main class then create another service class encapsulating an Async method m1您需要在配置类或主类中添加 @EnableAsync 然后创建另一个封装 Async 方法 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));
   }
}

you can use eventListener for creating event.您可以使用 eventListener 来创建事件。 And catch it in public method with EventListener annotation.并使用 EventListener 注释在公共方法中捕获它。 https://www.baeldung.com/spring-events https://www.baeldung.com/spring-events

The most simple and reliable way - run a thread.最简单可靠的方法——运行线程。 Try-final isn't good at all. Try-final 一点都不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM