【问题标题】:Spring and ThreadLocalSpring 和 ThreadLocal
【发布时间】:2014-11-19 14:54:41
【问题描述】:

我有一个 Spring Web 应用程序。每当在应用程序中出现错误时,我都会将错误放在错误上下文中(代码如下)。然后,我在异常处理程序中检索错误并返回一条消息。现在,假设输入 A,如果错误消息是“人不存在” 现在,对于第一次调用 spring web 应用程序,我得到了正确的输出:“Person is not there” 但是,对于第二个电话:我得到输出:“人不存在”,“人不存在” 因此,即使我使用的是 ThreadLocal,它也会记住我的最后一个请求。有人可以帮忙吗

我的 ErrorContext 代码:

公共类 ErrorContext {

private static ThreadLocal<ErrorContext> thisObj = new ThreadLocal<ErrorContext>();

/**
 * List of errors.
 */
private ArrayList<ApplicationError> errorList;

/**
 * Default private constructor.
 */
private ErrorContext() {
    errorList = new ArrayList<ApplicationError>();
}

/**
 * Initialize the ThreadLocal variable.
 */
public static void initialize() {
    if (thisObj.get() == null)
        thisObj.set(new ErrorContext());
    else {
        ErrorContext errorContext = (ErrorContext) thisObj.get();
        if (errorContext.getErrors() != null)
            errorContext.getErrors().clear();

    }
}

/**
 * Returns a new instance of the class.
 *
 * @return {@link ErrorContext}.
 */
public static ErrorContext getInstance() {
    if (thisObj.get() == null) {
        thisObj.set(new ErrorContext());
    }
    return (ErrorContext) thisObj.get();
}

/**
 * Add the error code to the List.
 *
 * @param errorCode
 *            errorCode obtained.
 */
public void addError(final ApplicationError error) {
    errorList.add(error);
}

/**
 * Return the List of errorCodes.
 *
 * @return List of error codes.
 */
public List<ApplicationError> getErrors() {
    return errorList;
}

/**
 * @author anbapri resets the context.
 */
public static void resetContext() {
    thisObj.set(new ErrorContext());
    ErrorContext errorContext = (ErrorContext) thisObj.get();
    if (errorContext.getErrors() != null)
        errorContext.getErrors().clear();
}

/**
 * Returns true if ErrorContext has error, otherwise false.
 *
 * @return
 */
public boolean hasError() {
    return !errorList.isEmpty();
}

}

我的响应处理程序 {
包 com.db.wscis.core.web.handler;

导入 java.util.ArrayList; 导入 java.util.List; 导入 java.util.Locale;

导入 javax.servlet.http.HttpServletRequest;

导入 org.apache.commons.logging.Log; 导入 org.apache.commons.logging.LogFactory; 导入 org.springframework.beans.factory.annotation.Autowired; 导入 org.springframework.context.MessageSource; 导入 org.springframework.context.i18n.LocaleContextHolder; 导入 org.springframework.http.HttpStatus; 导入 org.springframework.web.bind.annotation.ControllerAdvice; 导入 org.springframework.web.bind.annotation.ExceptionHandler; 导入 org.springframework.web.bind.annotation.ResponseBody; 导入 org.springframework.web.bind.annotation.ResponseStatus;

导入 com.db.wscis.core.util.exception.ApplicationError; 导入 com.db.wscis.core.util.exception.ApplicationException; 导入 com.db.wscis.core.util.exception.ErrorContext; 导入 com.db.wscis.core.web.model.ApplicationErrorRes; 导入 com.db.wscis.core.web.model.BaseResponse; 导入 com.db.wscis.core.web.model.ResponseObject;

@ControllerAdvice 公共类 RestExceptionProcessor {

private static final Log logger = LogFactory
        .getLog(RestExceptionProcessor.class);

@Autowired
private MessageSource messageSource;

@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public ResponseObject handleException(HttpServletRequest req, Exception excpt) {
    logger.error("",excpt);
//  Locale locale = LocaleContextHolder.getLocale();
    ResponseObject res = new ResponseObject();
//  String errorMessageDesc;
    res.setResultMessage("failure");
    //Business validation exception
    if (excpt instanceof ApplicationException) {
        List<ApplicationError> errorMessages = ErrorContext.getInstance()
                .getErrors();
        List<ApplicationErrorRes> errorMessageRes=new ArrayList<ApplicationErrorRes>();

        for(int i=0;i<errorMessages.size();i++){

        ApplicationErrorRes appErrorRes=    mapApplicationErrorToApplicationErrorRes(errorMessages.get(i));
        errorMessageRes.add(appErrorRes);

        }

        res.setApplicationErrors(errorMessageRes);
    } 
    //Other generic exception
    else {
        ArrayList<Exception> exceptionList=new ArrayList<Exception>();
        exceptionList.add(excpt);
        res.setExceptionList(exceptionList);
    }
    return res;
}

private ApplicationErrorRes mapApplicationErrorToApplicationErrorRes(ApplicationError appError){


    ApplicationErrorRes res=new ApplicationErrorRes();
    res.setErrorCode(appError.getErrorCode());
    res.setErrorLevel(appError.getErrorLevel());
    res.setErrorMessage(appError.getErrorMessage());

    return res;



}

} }

【问题讨论】:

  • 为什么不在ApplicationException中存储ApplicationError?

标签: spring thread-local


【解决方案1】:

解决这个问题的方法是在异常处理程序结束后执行 ErrorContext.resetContext()。

【讨论】:

    猜你喜欢
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2011-11-25
    • 2013-07-31
    相关资源
    最近更新 更多