Closed
Description
When a method is @Async
, @Value
variable becomes null
in any other final
methods (and, the @Async
method itself if it's final
) of the class.
Is this unavoidable due to Java Reflection spec?
Reproduction code here: https://github.com/taqqanori/spring-async-bug.
Reproduction code in short
@Service
public class AsyncService {
@Value("${spring.application.name}")
private String value;
@Async
public void async() {
// just declared, never called
}
public final void _final() {
// becomes null
System.out.println("async final: " + value);
}
public void nonFinal() {
// becomes "demo"
System.out.println("async non-final: " + value);
}
}
@Service
public class NonAsyncService {
@Value("${spring.application.name}")
private String value;
public final void _final() {
// becomes "demo"
System.out.println("non-async final: " + value);
}
public void nonFinal() {
// becomes "demo"
System.out.println("non-async non-final: " + value);
}
}
spring.application.name=demo
Output
async final: null
async non-final: demo
non-async final: demo
non-async non-final: demo
Environment
- OS: Ubuntu-20.04 on WSL2 on Windows11
- Java: openjdk-21
- Spring: Spring Boot 3.4.0 initialized from https://start.spring.io/ with "Spring Web" dependency
Thanks.