堆栈上有一个应用程序Spring Boot。应用程序有一个异步方法,它应该在后台与授权用户执行操作,但由于异步方法使用不同的上下文,它看不到授权用户。如何将主上下文传递给异步线程?
异步是通过@EnableAsync和@Async 实现的。
SpringAsync 配置:
@Configuration
@EnableAsync
public class SpringAsyncConfig {
@Bean(name = "asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(3);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("AsyncThread-");
executor.initialize();
return executor;
}
}
如果我们谈论的是访问
SecurityContextHolder.getContext(),那么您可以使用DelegatingSecurityContextAsyncTaskExecutor然后上下文将包含带有注释的方法内的身份验证数据
@Async:更多细节在这里