Brian
Brian

Reputation: 616

Spring Boot Scopes

I am trying to do something similar to the following. I want to be able to set infoVar in myController and get it in MyResponseEntityExceptionHandler. I have tried setting the correct scope (i think Request) but I keep getting errors similar to:

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;
  }
}

error handling

@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;
    }
}

infoVar

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

Upvotes: 0

Views: 368

Answers (2)

Brian
Brian

Reputation: 616

I did come up with an solution but I am not in love with it. I feel that there should be a way to do this with beans instead of adding to the 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;
  }
}

Error Handling

@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;
    }
}

InfoVar

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

Upvotes: 1

Mayank Tripathi
Mayank Tripathi

Reputation: 388

Try Registering a RequestContextListener listener in web.xml file.

<web-app ...>
   <listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
   </listener>
</web-app>

Upvotes: 0

Related Questions