我正在尝试在基于Spring的Web应用程序中使用并发机制。所以我使用下面的方法来使用线程概念来获取员工的详细信息。但由于弹簧上下文在线程上为空,我的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();
}
在&#34; empService.getEmployeeDetails&#34;方法,我使用下面的代码引用Spring上下文:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<GrantedAuthority> authorities = auth.getAuthorities();
但是在访问spring上下文时我得到空指针异常。
有人可以帮我这个吗?
答案 0 :(得分:1)
您可以利用org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor
。尝试这样的事情:
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(10);
threadPool.initialize();
TaskExecutor taskExecutor = new DelegatingSecurityContextAsyncTaskExecutor(threadPool);
ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(taskExecutor);
...