简体   繁体   English

请求范围的bean的Bean创建错误

[英]Bean creation errors for request-scoped beans

When a Spring bean is annotated with SCOPE_REQUEST , it is created and destroyed every time a HTTP request is received by the servlet. 当使用SCOPE_REQUEST注释Spring bean时,每次servlet接收到HTTP请求时都会创建并销毁它。 If this bean creation fails, a server error is sent back to the caller. 如果此Bean创建失败,则会将服务器错误发送回调用方。

In this trivial example, the creation of the MyInputs bean is dependent on the contents of the HTTP request. 在这个简单的示例中, MyInputs bean的创建取决于HTTP请求的内容。

@Configuration
class ApplicationConfiguration {

    @Bean
    @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
    public MyInputs myInputs(HttpServletRequest request) {

        String header1 = request.getHeader("header1");
        if (header1 == null) {
            throw new MyException("header1 is missing");
        }
        return new MyInputs(header1);
    }
}

If the HTTP request does not contain a required header, a BeanCreationException will be thrown. 如果HTTP请求不包含必需的标头,则将抛出BeanCreationException This is translated into an unhelpful "500 Internal Server Error" response. 这被转换为无用的“500内部服务器错误”响应。

I would like to return a more user-friendly response code and body, for example, a "400 Bad Request" with a helpful message. 我想返回一个更加用户友好的响应代码和正文,例如,“400 Bad Request”和一条有用的消息。 How do I customize this response translation? 如何自定义此响应转换? I cannot find any lifecycle hooks which will allow this. 我找不到任何允许这样做的生命周期钩子。


Note: This is how the request-scoped bean is consumed: 注意:这是使用请求范围的bean的方式:

@RestController
public class MyController {

    private final Provider<MyInputs> myInputsProvider;

    @Autowired
    public MyController(Provider<MyInputs> myInputsProvider) {

        this.myInputsProvider = myInputsProvider;
    }

    @GetMapping("/do-stuff")
    public void doStuff() {

        // Get the inputs for the current request
        MyInputs myInputs = myInputsProvider.get();

        // ...
    }
}

You can use @ControllerAdvice annotation in order to handle exceptions after are thrown. 您可以使用@ControllerAdvice批注来处理抛出后的异常。

Also you need to use @ExceptionHandler in order to handle the exception. 您还需要使用@ExceptionHandler来处理异常。

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MyException.class)
    public final ResponseEntity<CustomError> handleException(MyException ex, WebRequest request) {
        CustomError error = new CustomError();            
        error.setMessage(ex.getMessage());
        error.setStatus(HttpStatus.BAD_REQUEST);
        return new ResponseEntity<>(error, null, HttpStatus.BAD_REQUEST);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 请求范围的bean和数据模型初始化? - Request-scoped beans and datamodel initialization? 在HandlerIntercaptor中访问请求范围的bean - accessing a request-scoped bean in HandlerIntercaptor 为什么在没有请求的情况下注入请求范围的bean? - Why can I inject request-scoped beans in the absence of a request? 请求范围的 bean 在使用 Cucumber 的 Spring 测试中不起作用 - Request-scoped beans not working in Spring tests with Cucumber 根据请求参数自动装配请求范围的bean - Autowiring a request-scoped bean based on a request parameter Spring请求范围的Bean-所有字段为空/空 - Spring request-scoped bean - all fields null/empty Spring:如何将HttpServletRequest注入请求范围的bean? - Spring: how do I inject an HttpServletRequest into a request-scoped bean? 为什么不从表单值创建请求范围的bean? - Why request-scoped bean is not created from form values? 如何在组件注释的 bean 中使用会话或请求范围的 bean? - How can I use a session or request-scoped bean in a component annotated bean? 通过AJAX使用请求范围的Bean向h:dataTable添加一行,而不会丢失行数据 - Add a row to h:dataTable via AJAX with request-scoped bean without losing the row data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM