'Accessing AWS Lambda Context from Spring Cloud Function

I'm using Spring Cloud Function 1.0.0.RELEASE and the corresponding AWS adapter to run it in AWS lambda. Is there any way to retrieve the lambda function context from the Spring application context?

I know if you implement the RequestHandler interface yourself, then you get the Context object as the second parameter of the handleRequest method (see below), but since the SpringBootRequestHandler is handling this, it's not clear to me how to access the Context object. Any ideas?

Example of implementing RequestHandler directly

public class LambdaRequestHandler implements RequestHandler<String, String> {

    public String handleRequest(String input, Context context) {
        context.getLogger().log("Input: " + input);
        return "Hello World - " + input;
    }
}

Deferring the implementation of RequestHandler to SpringBootRequestHandler

public class SomeFunctionHandler 
      extends SpringBootRequestHandler<SomeRequest, SomeResponse> {
}


Solution 1:[1]

SomeFunctionHandler extends the SpringBootRequestHandler, so it can override the handleRequest method to get access to the AWS lambda Context object.

public class SomeFunctionHandler extends SpringBootRequestHandler<SomeRequest, SomeResponse> {

    private static final Logger logger = LoggerFactory.getLogger(SomeFunctionHandler.class);

    @Override
    public Object handleRequest(SomeRequest event, Context context) {
        logger.info("ARN=" + context.getInvokedFunctionArn());
        return super.handleRequest(event, context);
    }

}

Solution 2:[2]

In case you are exposing Function as a bean, you can simply Autowire the Context object.

Example:


    @Autowired
    private Context context;

    @Bean
    public Function<String, String> uppercase() {
        logger.info("ARN=" + context.getInvokedFunctionArn());
        return value -> {
            if (value.equals("exception")) {
                throw new RuntimeException("Intentional exception which should result in HTTP 417");
            }
            else {
                return value.toUpperCase();
            }
        };
    }

Source : this answer.

Solution 3:[3]

If you're using spring-cloud-function-adapter-aws only, @Autowired might not work.

However, you could wrap your input with org.springframework.messaging.Message.

public class FooHandler implements Function<Message<DynamodbEvent>, String> {

  @Override
  public String apply(Message<DynamodbEvent> message) {
    // Get AWS Lambda Context
    Context context = message.getHeaders().get("aws-context", Context.class);
    assert context != null;
    
    // Get the original input
    DynamodbEvent payload = message.getPayload();
    return payload.toString();
  }
}

Source:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 emerson
Solution 2 Smile
Solution 3 Adi