Spring MVC:如何在ResponseEntity体中返回不同的类型

时间:2013-10-31 15:33:56

标签: java spring generics spring-mvc

在我的请求处理程序中,我想进行一些验证,并根据验证检查的结果,我将返回不同的响应(成功/错误)。因此,我为响应对象创建了一个抽象类,并为失败案例和成功案例创建了2个子类。代码看起来像这样,但它不编译,抱怨errorResponse和successResponse无法转换为AbstractResponse。

我是Java Generic和Spring MVC的新手,所以我不知道解决这个问题的简单方法。

@ResponseBody ResponseEntity<AbstractResponse> createUser(@RequestBody String requestBody) {
    if(!valid(requestBody) {
        ErrorResponse errResponse = new ErrorResponse();
        //populate with error information
        return new ResponseEntity<> (errResponse, HTTPStatus.BAD_REQUEST);
    }
    createUser();
    CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
    // populate with more info
    return new ResponseEntity<> (successResponse, HTTPSatus.OK);
}

2 个答案:

答案 0 :(得分:22)

这里有两个问题:

  • 必须更改您的返回类型以匹配两个响应子类ResponseEntity<? extends AbstractResponse>
  • 当您实例化您的ResponseEntity时,您无法使用简化的&lt;&gt;语法必须指定要使用的响应类new ResponseEntity<ErrorResponse> (errResponse, HTTPStatus.BAD_REQUEST);

    @ResponseBody ResponseEntity<? extends AbstractResponse> createUser(@RequestBody String requestBody) {
        if(!valid(requestBody) {
            ErrorResponse errResponse = new ErrorResponse();
            //populate with error information
            return new ResponseEntity<ErrorResponse> (errResponse, HTTPStatus.BAD_REQUEST);
        }
        createUser();
        CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
        // populate with more info
        return new ResponseEntity<CreateUserSuccessResponse> (successResponse, HTTPSatus.OK);
    }
    

答案 1 :(得分:10)

另一种方法是使用错误处理程序

@ResponseBody ResponseEntity<CreateUserSuccessResponse> createUser(@RequestBody String requestBody) throws UserCreationException {
    if(!valid(requestBody) {
        throw new UserCreationException(/* ... */)
    }
    createUser();
    CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
    // populate with more info
    return new ResponseEntity<CreateUserSuccessResponse> (successResponse, HTTPSatus.OK);
}

public static class UserCreationException extends Exception {
    // define error information here
}

@ExceptionHandler(UserCreationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse handle(UserCreationException e) {
    ErrorResponse errResponse = new ErrorResponse();
    //populate with error information from the exception
    return errResponse;
}

这种方法可以返回任何类型的对象,因此不再需要成功案例和错误案例(甚至案例)的抽象超类。