Java SecurityContextHolder的ExecutorService

Java SecurityContextHolder的ExecutorService,java,spring,spring-security,executorservice,security-context,Java,Spring,Spring Security,Executorservice,Security Context,我使用ExecutorService将方法的单线程执行更改为多线程执行。 它在内部调用SecurityContextHolder,引发异常: 原因:java.lang.Exception:在安全上下文中找不到身份验证对象。 位于com.LoggedInUser.getLoggedInUser(LoggedInUser.java:25) 在com.Controller.submitate上(RateController.java:242) 我的代码: method(){ Future<Re

我使用ExecutorService将方法的单线程执行更改为多线程执行。 它在内部调用SecurityContextHolder,引发异常:

原因:java.lang.Exception:在安全上下文中找不到身份验证对象。 位于com.LoggedInUser.getLoggedInUser(LoggedInUser.java:25) 在com.Controller.submitate上(RateController.java:242)

我的代码:

method(){

Future<Results> future = executor.submit(new callableClass(form, request));

            if (null != future.get()) {
                rates = future.get();
            }}
}


class callableClass implements Callable<RateResults> {

    private Form form;
    private HttpServletRequest request;

    public RateShippmentCaller(Form form, HttpServletRequest request) {
        super();
        this.form = form;
        this.request = request;
    }

    @Override
    public Results call() throws Exception {
        return controller.submit(form, request);
    }

}

submit(form, request){
LoggedInUser.getLoggedInUser()
}

class LoggedInUser{
    getLoggedInUser(){
       SecurityContext **secCtx** = SecurityContextHolder.getContext();
        Authentication authentication = secCtx.getAuthentication();
        if (authentication == null) {
            throw new Exception("Authentication object not found in security context.");
        }
    }
}
method(){
Future=executor.submit(新callableClass(表单、请求));
if(null!=future.get()){
rates=future.get();
}}
}
类callableClass实现可调用{
私人形式;
私有HttpServletRequest;
public RateShipmentCaller(表单,HttpServletRequest){
超级();
this.form=形式;
this.request=请求;
}
@凌驾
公共结果调用()引发异常{
返回控制器。提交(表格、请求);
}
}
提交(表格、请求){
LoggedInUser.getLoggedInUser()
}
类LoggedInUser{
getLoggedInUser(){
SecurityContext**secCtx**=SecurityContextHolder.getContext();
Authentication=secCtx.getAuthentication();
if(身份验证==null){
抛出新异常(“在安全上下文中找不到身份验证对象”);
}
}
}

请让我知道如何避免例外secCtx返回空值。

尝试设置以下安全上下文持有者策略:

SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
注意,只有在每次创建新线程时,才应该使用线程池

传递上下文的另一种方式:

Runnable runnable = new Runnable() {
    public void run() {
        // you’ll be able to access the context here
    }
};
SecurityContext context = SecurityContextHolder.getContext();
DelegatingSecurityContextRunnable wrappedRunnable =
    new DelegatingSecurityContextRunnable(runnable, context);

new Thread(wrappedRunnable).start();