繁体   English   中英

传播Spring安全上下文

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM