我目前正在尝试使用 Spring Boot 创建 REST API。
我正在使用 ResponseEntity 提供响应,并另外创建一个用于合并响应的对象。
代码目前看起来像这样
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RestResponse<T> {
private Integer status;
private HttpStatus httpStatus;
private String path;
private String message;
private T data;
}
如果在服务层
DeviceEntity resultCreate = deviceMapper.getDeviceByDeviceIndex(deviceEntity.getDeviceIndex());
将结果发送至
return RestResponse.builder()
.status(200)
.httpStatus(HttpStatus.OK)
.message("Success")
.data("")
.build();
return RestResponse.builder()
.status(ase.statusCode())
.httpStatus(HttpStatus.valueOf(ase.statusCode()))
.message(ase.awsErrorDetails().errorCode())
.data("")
.build();
当我们使用try catch返回RestResponse并且控制器将其放入responseEntity并将其返回给我们时,我们可以使用
这是正确的结构吗?
包装不是应该在控制器层完成吗?
如果需要修改,该如何修改?
我目前认为我需要在控制器层创建一个 RestResponse 对象。
以下是对您的疑问的全面答复,结合最佳实践并解决您的疑虑:
要点:
RestResponse
对象来保持关注点的清晰分离。推荐结构:
控制器层:
RestResponse
对象。RestResponse
包裹在 ResponseEntity
中并退回。@RestController
@RequestMapping("/api/devices")
public class DeviceController {
private final DeviceService deviceService;
@GetMapping("/{index}")
public ResponseEntity<RestResponse<DeviceEntity>> getDeviceByIndex(@PathVariable String index) {
DeviceEntity device = deviceService.getDeviceByDeviceIndex(index);
if (device == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(
RestResponse.<DeviceEntity>builder()
.status(200)
.httpStatus(HttpStatus.OK)
.message("Success")
.data(device)
.build()
);
}
}
服务层:
@Service
public class DeviceService {
private final DeviceMapper deviceMapper;
public DeviceEntity getDeviceByDeviceIndex(String deviceIndex) {
return deviceMapper.getDeviceByDeviceIndex(deviceIndex);
}
}
异常处理:
@ExceptionHandler
来处理异常并构造适当的 RestResponse
对象。其他注意事项:
RestResponse
字段。通过遵循此结构,您将使用 Spring Boot 创建结构良好、适应性强且用户友好的 REST API。