[英]Propagate Spring security Context
我正在嘗試在基於Spring的Web應用程序中使用並發機制。 因此,我已使用以下方法使用線程概念來獲取員工詳細信息。 但是由於Spring上下文在線程上為null,所以我失敗了Null指針異常。
我使用了以下代碼:
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(10);
threadPool.initialize();
ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(threadPool);
List<Callable<Employee>> tasks = new ArrayList<Callable<Employee>>();
for (int i = 0; i < employeeArr.length; i++) {
final int value = i;
tasks.add(new Callable<Employee>() {
public Employee call() throws Exception {
return empService.getEmployeeDetails(employeeArr[value], finalFromDate);
}
});
}
try {
List<Future<Employee>> result = adapter.invokeAll(tasks);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i).get());
}
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
在“ empService.getEmployeeDetails”方法中,我通過使用以下代碼來引用Spring上下文:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<GrantedAuthority> authorities = auth.getAuthorities();
但是在訪問spring上下文時,我得到了空指針異常。
有人可以幫我嗎?
您可以利用org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor
。 嘗試這樣的事情:
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(10);
threadPool.initialize();
TaskExecutor taskExecutor = new DelegatingSecurityContextAsyncTaskExecutor(threadPool);
ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(taskExecutor);
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.