The methods annotated with @Async can accept any method arguments.
Only Future and void return type for async method are supported
Pre Spring 6, the retuned value other than Future and void were allowed, but they always returned null if it's not Future or void.
Starting Spring 6 only void and Future return typed are allowed, not doing so will throw runtime exception.
Exception in thread "main" java.lang.IllegalArgumentException: Invalid return type for async method (only Future and void supported): class java.lang.String
Example
package com.logicbig.example;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
@Async
public void runTask(String message) {
System.out.printf("Running task thread: %s%n",
Thread.currentThread().getName());
System.out.printf("message: %s%n", message);
System.out.println("task ends");
}
}
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@ComponentScan
public class AsyncArgAndReturnValueExample {
public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
AsyncArgAndReturnValueExample.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling MyBean#runTask() thread: %s%n",
Thread.currentThread().getName());
bean.runTask("Test message");
System.out.println("call MyBean#runTask() returned");
}
}
Outputcalling MyBean#runTask() thread: com.logicbig.example.AsyncArgAndReturnValueExample.main() call MyBean#runTask() returned Running task thread: SimpleAsyncTaskExecutor-1 message: Test message task ends
Example ProjectDependencies and Technologies Used: - spring-context 6.2.12 (Spring Context)
Version Compatibility: 4.0.0.RELEASE - 6.2.12 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 25
- Maven 3.9.11
|