Fix Java @Async Not Working
Using the @Async annotation in Java to achieve asynchronous method calls requires the following steps:
- Enable asynchronous support in the configuration file of Spring Boot.
spring.aop.proxy-target-class=true
- Add the @EnableAsync annotation to the main class of Spring Boot to enable asynchronous calling.
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- Add the @Async annotation on methods that need to be executed asynchronously.
@Service
public class MyService {
@Async
public CompletableFuture<String> asyncMethod() {
// 异步执行的方法体
}
}
- Obtain the results of asynchronous methods using CompletableFuture.
@Service
public class MyService {
@Async
public CompletableFuture<String> asyncMethod() {
// 异步执行的方法体
return CompletableFuture.completedFuture("异步方法执行完成");
}
}
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/async")
public CompletableFuture<String> asyncEndpoint() {
return myService.asyncMethod();
}
}
If the @Async annotation is still not working, it may be due to the following reasons:
- Other methods in the same class are calling the asynchronous method. Spring cannot intercept the asynchronous method for processing when called within the same class. The asynchronous method needs to be placed in a different class for proper handling.
- The asynchronous method was not detected by the Spring container. Make sure the class containing the asynchronous method is annotated with @Component or @Service, and ensure it is properly scanned by the Spring container.
- The asynchronous method is not being called by a public method. Ensure that the asynchronous method is called by a public method, not by a private method within the same class.
- The wrong proxy mode was used. In the Spring configuration file, set spring.aop.proxy-target-class to true to use the CGLIB proxy mode. If set to false, the default JDK dynamic proxy mode will be used.
If the above solutions do not work, you can try rebuilding the project, clearing the cache, and ensuring that the Spring Boot version you are using supports the usage of the @Async annotation.