NullPointer with @Autowire HttpServletRequest

Viewed 38

I have the following code:

package com.example.helloworld;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.annotation.RequestScope;

@RestController
public class HelloWorldController {
  @GetMapping("/")
  public ResponseEntity<String> getGet(
      @Autowired Foo foo) {

    foo.sayHi();

    return new ResponseEntity<>("OK", HttpStatus.OK);
  }
}

@Component
@RequestScope
class Foo {

  private @Autowired HttpServletRequest request;

  public void sayHi() {
    var name = this.request.getHeader("x-user-name");
    System.out.println("Hi " + name);
  }
}

When I try to curl with curl -H x-user-name:capybara http://localhost:8080, the following error is produced:

2022-09-09 17:07:28.623 ERROR 26350 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "javax.servlet.http.HttpServletRequest.getHeader(String)" because "this.request" is null] with root cause

java.lang.NullPointerException: Cannot invoke "javax.servlet.http.HttpServletRequest.getHeader(String)" because "this.request" is null
        at com.example.helloworld.Foo.sayHi(HelloWorldController.java:32) ~[classes!/:0.0.1-SNAPSHOT]
        at com.example.helloworld.HelloWorldController.getGet(HelloWorldController.java:19) ~[classes!/:0.0.1-SNAPSHOT]
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
        at 
    ...

Why is this.request null? Giving the popularity of https://stackoverflow.com/a/3324233/2287586, seems like this should work, what am I missing?

1 Answers

It doesn't work becuse it needs to be a Singleton bean and you have @RequestScope. Maybe try this:

((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
Related