简体   繁体   English

传播Spring安全上下文

[英]Propagate Spring security Context

I am trying to use concurrent mechanism in my Spring based web application. 我正在尝试在基于Spring的Web应用程序中使用并发机制。 so that I have used the below method to use thread concept to get the employee details. 因此,我已使用以下方法使用线程概念来获取员工详细信息。 but I have failed with Null pointer exception due to spring context is null on threads. 但是由于Spring上下文在线程上为null,所以我失败了Null指针异常。

I have used the below code: 我使用了以下代码:

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();
            }

In the "empService.getEmployeeDetails" method, I am referring the Spring context by using below code: 在“ empService.getEmployeeDetails”方法中,我通过使用以下代码来引用Spring上下文:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Collection<GrantedAuthority> authorities = auth.getAuthorities();

But I am getting null pointer exception when accessing the spring context. 但是在访问spring上下文时,我得到了空指针异常。

could anyone please help me on this? 有人可以帮我吗?

You can take advantage of org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor . 您可以利用org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor Try something like this: 尝试这样的事情:

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