我正在使用ExecutorService将方法的单线程更改为多线程执行。它在内部调用SecurityContextHolder,并抛出异常:
原因:java.lang.Exception:在安全上下文中找不到身份验证对象。在com.LoggedInUser.getLoggedInUser(LoggedInUser.java:25)在com.Controller.submitRate(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.");
}
}
}
[请让我知道如何避免例外。 secCtx返回空值。
尝试设置以下安全上下文持有者策略:
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
注意,只有每次都创建一个新线程时,才应使用此线程池。
传输上下文的另一种方法:
Runnable runnable = new Runnable(){公共无效run(){//您将可以在此处访问上下文}};SecurityContext上下文= SecurityContextHolder.getContext();DelegatingSecurityContextRunnable包装的Runnable =新的DelegatingSecurityContextRunnable(runnable,context);
新线程(wrappedRunnable).start();