Skip to content

Instantly share code, notes, and snippets.

@pavelfomin
Created May 16, 2025 15:17
Show Gist options
  • Save pavelfomin/96e420255ce30cab6e7431c122bb9db6 to your computer and use it in GitHub Desktop.
Save pavelfomin/96e420255ce30cab6e7431c122bb9db6 to your computer and use it in GitHub Desktop.
DelegatingSecurityContextAsyncTaskExecutor bootstrap that requires custom taskExecutor for some reason
import org.springframework.boot.task.ThreadPoolTaskExecutorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor;
@Configuration
public class AsyncTaskExecutorConfiguration {
/**
* Have to define custom ThreadPoolTaskExecutor bean to be used by DelegatingSecurityContextAsyncTaskExecutor to
* work around for error creating bean with name 'delegatingSecurityContextAsyncTaskExecutor': Requested bean is currently in creation:
* Is there an unresolvable circular reference or an asynchronous initialization dependency?
* Using ThreadPoolTaskExecutorBuilder to get the default configuration.
*/
@Bean
public AsyncTaskExecutor taskExecutor(ThreadPoolTaskExecutorBuilder builder) {
return builder.build();
}
/**
* Spring SecurityContext is bound to a ThreadLocal, and is not available in @Async methods, which run in separate threads.
* To propagate the SecurityContext, Spring provides DelegatingSecurityContextAsyncTaskExecutor.
*/
@Bean
public DelegatingSecurityContextAsyncTaskExecutor delegatingSecurityContextAsyncTaskExecutor(AsyncTaskExecutor delegate) {
return new DelegatingSecurityContextAsyncTaskExecutor(delegate);
}
}
@pavelfomin
Copy link
Author

if @scheduled annotation is used then it works w/out custom taskExecutor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment