Spring和ThreadLocal

时间:2014-11-19 14:54:42

标签: spring thread-local

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

我的ErrorContext代码:

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

}

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

import java.util.ArrayList; import java.util.List; import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

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

import com.db.wscis.core.util.exception.ApplicationError; import com.db.wscis.core.util.exception.ApplicationException; import com.db.wscis.core.util.exception.ErrorContext; import com.db.wscis.core.web.model.ApplicationErrorRes; import com.db.wscis.core.web.model.BaseResponse; import 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;



}

} }

1 个答案:

答案 0 :(得分:1)

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