java - Spring Boot 范围

标签 java spring spring-boot

我正在尝试做类似以下的事情。我希望能够在 myController 中设置 infoVar 并在 MyResponseEntityExceptionHandler 中获取它。我尝试设置正确的范围(我认为是请求),但我不断收到类似以下内容的错误:

Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

Controller

@RestController()
public class myController() {
  @Autowired private InfoVar infoVar;

  @PostMapping(path = "/stuff")
  public @ResponseBody sutff getStuff(@RequestBody String string)   throws Exception {
    infoVar.setVar("Test123");
    return stuff;
  }
}

错误处理

@ControllerAdvice
@RestController
public class MyResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @Autowired private InfoVar infoVar

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleStuff(Exception ex, WebRequest request) {
        infoVar.getVar();
        return stuff;
    }
}

信息变量

@Component
@Scope("request")
public class InfoVar{
    private String infoVar;
getter and setter for infovar
}

最佳答案

我确实想出了一个解决方案,但我不喜欢它。我觉得应该有一种方法可以用 beans 来做到这一点,而不是添加到 WebRequest 中。

Controller

@RestController()
public class MyController() {

  @PostMapping(path = "/stuff")
  public @ResponseBody sutff getStuff(@RequestBody String string)   throws Exception {
    InfoVar infoVar = new InfoVar();
    infoVar.setVar("Test123");
    webRequest.setAttribute("infoVar", infoVar, WebRequest.SCOPE_REQUEST);
    return stuff;
  }
}

错误处理

@ControllerAdvice
public class MyResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleStuff(Exception ex, WebRequest request) {
        InfoVar infoVar = (InfoVar) request.getAttribute("infoVar", WebRequest.SCOPE_REQUEST);
        infoVar.getVar();
        return stuff;
    }
}

信息变量

public class InfoVar{
    private String var;
getter and setter for var
}

关于java - Spring Boot 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59740937/

相关文章:

java - Spring Data MongoDB,按长值搜索

java - Spring 将文件映射到 Url/URI

java - 类 java.util.LinkedHashMap 无法转换为类 java.lang.String(java.util.LinkedHashMap 和 java.lang.String

java - Java 中的 Curl oAuth 等效项

java - 日历 DATE 麻烦

java - 删除 Java 中的第一个空格

java - com.springboot.todoController.TodoController 中的字段 todoService 需要类型为 'com.springboot.todo.TodoService' 的 bean,但无法找到

java - Eclipse Google 插件不会为 Web 应用程序启动服务器

java - MessageStore 支持 QueueChannel,带有 Spring Integration+ Java Config

java - REST - HTTP 状态 405;不允许的方法;请求方法 'PUT'不支持错误