Async Method In Configuration Class
ID |
java.async_annot_methods_declared_config |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability |
Description
Reports methods annotated @Async inside a @Configuration class. @Configuration classes are processed while Spring is still assembling the bean definitions that make up the application context, before the executor Spring’s @Async support relies on is guaranteed to exist.
Rationale
@Bean methods on a @Configuration class run as part of context initialization, not as ordinary application code. Marking one @Async asks Spring to hand it off to a task executor that has not necessarily been configured yet at that point in the startup sequence, so the annotation is unreliable at best and silently ignored at worst.
// Bad: @Async has no dependable effect during configuration processing
@EnableAsync
@Configuration
public class MailConfig {
@Async
public void warmUpConnectionPool() {
// ...
}
}
Remediation
Move the asynchronous work out of the @Configuration class into an ordinary @Service (or similar) bean, where @Async runs after the application context — and its executor — are fully initialized.
// Good: the asynchronous work lives in a regular service bean
@Service
public class MailWarmupService {
@Async
public void warmUpConnectionPool() {
// ...
}
}