Reputation: 181290
Straightforward question. Is there a way to tell in a Spring Application (ApplicationContext or similar) if async
is enabled?
I have a configuration bean:
@Configuration
@EnableAsync
public class MyConfig {}
I would like to know, in my code, if async
is actually enabled.
Upvotes: 2
Views: 990
Reputation: 407
Thanks Pablo for your excellent question!
Indeed, we should have a clear error when we start using Async without enabling it. I don't know if in Spring (boot) there is a clear way to enforce this but I found at least a clear way to check explicitly if async is enabled. Unfortunately the check on existence of the AbstractAsyncConfiguration bean didn't work in my case (Spring 4 application?). So I had to figure out another way. And this might be more reliable because it actually uses the behaviour, instead of checking the machinery.
For this you can create a bean with one async method that returns a value, say a String. When async is enabled it will always return null since it cannot return the actual value that is returned from the asynchronously called method implementation. When called synchronously it will in fact return that value, which indicates async is not enabled.
Here is the code example for the check (obviously either way, but here I use the check from a postconstruct somewhere before using actual async stuff in my application):
private void check() {
if ("sync".equals(asyncCheck.check())){
throw new RuntimeException("Async should be enabled.");
}
}
And then the code of the AsyncCheck interface.
public interface AsyncCheck {
String check();
}
And the AsyncCheckImpl bean.
@Component
public class AsyncCheckImpl implements AsyncCheck {
@Override
@Async
public String check() {
return "sync";
}
}
Side note is that obviously it is not recommended to return anything from a asynchronous method, but in this rare case it is kind of what you actually want.
Upvotes: 2