4

I developed a project using RestController in Spring Boot and it worked without error.

Now I use AWS lambda but I get a null pointer exception when I try to inject a Spring bean to the the lambda handler:

public class HelloWorldHandler implements RequestHandler<Map<String, Object>, Object> {

  @Autowired
  private IUserService userservice;

  public Object handleRequest(Map<String, Object> input, final Context context) {

    Map<String, String> headers = new HashMap<>();
    headers.put("Content-Type", "application/json");

    User testUser = new User();
    testUser.setId("10");
    testUser.setLastname("test_lastname");
    testUser.setMail("test@al.com");

    userservice.addUser(testUser);

    return new GatewayResponse("success", headers, 200);
  }
}

Exception:

{
  "errorMessage": "java.lang.NullPointerException",
  "errorType": "java.lang.NullPointerException",
  "stackTrace": [
    "HelloWorldHandler.handleRequest(HelloWorldHandler.java:30)",
    "HelloWorldHandler.handleRequest(HelloWorldHandler.java:21)"
  ]
}
Attila T
  • 577
  • 1
  • 4
  • 18
sameh
  • 127
  • 2
  • 10
  • Please include the full stack trace. – Ortomala Lokni Jun 25 '17 at 10:38
  • @OrtomalaLokni START RequestId: 2b718de0-5999-11e7-8a84-1d1d4d448537 Version: $LATEST java.lang.NullPointerException: java.lang.NullPointerException java.lang.NullPointerException at com.aws.codestar.projecttemplates.handler.HelloWorldHandler.handleRequest(HelloWorldHandler.java:29) at com.aws.codestar.projecttemplates.handler.HelloWorldHandler.handleRequest(HelloWorldHandler.java:23) END RequestId: 2b718de0-5999-11e7-8a84-1d1d4d448537 REPORT RequestId: 2b718de0-5999-11e7-8a84-1d1d4d448537 Duration: 2613.73 ms Billed Duration: 2700 ms Memory Size: 128 MB Max Memory Used: 47 MB – sameh Jun 25 '17 at 11:27
  • Please edit your question and add the exception to it. – Ortomala Lokni Jun 25 '17 at 11:53
  • Possible duplicate of [amazon aws lamba function with spring autowired dependencies](https://stackoverflow.com/questions/35753573/amazon-aws-lamba-function-with-spring-autowired-dependencies) – Attila T Feb 09 '18 at 18:58

1 Answers1

0

HelloWorldHandler is not a Spring component so you can't just inject a bean to that class. Spring context is not loaded even. So it can't work :)

You can use Spring Cloud Function to run context and get access to all Spring feature including "Autowired".

Or you can try this one: https://github.com/MelonProjectCom/lambda-http-router

Easy to use and allows to run multiple handlers in single lambda:

    @PathPostMapping("/example/test")
    public String example(@Body String body) {
        return "Hello World! - body: " + body;
    }
Prime171
  • 11
  • 1