使用 @Async 註解的方法必須返回 Future 或 void

此規則標示 Java 方法註解為 org.springframework.scheduling.annotation.Async 以外的類型的 void, Future<t>, CompletableFuture<t>ListenableFuture<t>.

在 Spring Framework 6 中,這些回傳類型要求在執行時會被嚴格強制執行。 任何 @Async 方法返回不支援的類型,現在會拋出 Exception。

以下範例展示了使用 @Async 且回傳類型符合規範的方法的有效用法。


import org.springframework.scheduling.annotation.Async;
import java.util.concurrent.Future;
import java.util.concurrent.CompletableFuture;
import org.springframework.util.concurrent.ListenableFuture;

public class ValidAsyncMethods {
	
    @Async
    public void asyncVoid() {
    }
    @Async
    public Future<String> asyncFuture() {
        return null;
    }
    @Async
    public CompletableFuture<Integer> asyncCompletableFuture() {
        return null;
    }
    @Async
    public ListenableFuture<String> asyncListenableFuture() {
        return null;
    }
}

如需相關資訊,請參閱下列資源: