EN
Spring Boot 2 - running async tasks
4
points
In this short article, we would like to show how to run async tasks in Spring Boot 2 application.
As async task we understand task that can be run in the separated thread.
Quick solution:
- add
@EnableAsyncannotation to the application configuration class,- add
@Asyncannotation to the application component method,- call asynchronous method like normal method.
Practical example
In this section, you can find easy way to run some methods in async mode. Each async method should have @Async annotation. Spring Boot 2 adds to that methods proxy and runs them in executor on calls.
DemoApplication.java file:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
AsyncConfig.java file:
package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync // <------------------------------------ REQUIRED
public class AsyncConfig { }
Hint:
@EnableAsyncannotation be added to any configuration.
TaskController.java file:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TaskController {
@Autowired
private TaskService taskService;
@RequestMapping("/test")
@ResponseBody
public void test() throws Throwable {
this.taskService.doTask(); // runs async task
}
}
TaskService.java file:
package com.example.demo;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class TaskService {
@Async // <-------------------------------------- REQUIRED
public void doTask() throws Throwable {
Thread.sleep(1000);{ // replace it with some operations ...
}
}
Warnings:
@Asyncmethod must be public,@Asyncmethod cannot call itself.