This example shows a service with an async method that waits 1 second then returns a message. The main runner calls it without blocking, then waits for the result to print.
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.CompletableFuture;
@Configuration
@EnableAsync
public class AsyncConfig {
}
@Service
public class AsyncService {
@Async
public CompletableFuture<String> asyncTask() {
try {
Thread.sleep(1000); // simulate delay
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return CompletableFuture.completedFuture("Task Completed");
}
}
// Usage in another component
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
@Component
public class AppRunner implements CommandLineRunner {
@Autowired
private AsyncService asyncService;
@Override
public void run(String... args) throws Exception {
System.out.println("Starting async call");
CompletableFuture<String> future = asyncService.asyncTask();
System.out.println("Async call made");
System.out.println("Result: " + future.get());
}
}