Skip to content

Quick start Spring

Stefano Buliani edited this page Apr 14, 2017 · 33 revisions

You can use the aws-serverless-java-container library to run a Spring application in AWS Lambda. You can use the library within your Lambda handler to load your Spring application and proxy events to it.

Import dependencies

The first step is to import the Spring implementation of the library:

<dependency>
    <groupId>com.amazonaws.serverless</groupId>
    <artifactId>aws-serverless-java-container-spring</artifactId>
    <version>LATEST</version>
</dependency>

This will automatically also import the aws-serverless-java-container-core and aws-lambda-java-core libraries.

Create the Lambda handler

In your application package declare a new class that implements Lambda's RequestHandler interface. If you have configured API Gateway with a proxy integration, you can use the built-in POJOs AwsProxyRequest and AwsProxyResponse.

The next step is to declare the container handler object. The library exposes a utility static method that configures a SpringLambdaContainerHandler object for AWS proxy events. The method receives a class annotated with Spring's @Configuration that defines your application. The object should be declared as a class property and be static. By doing this, Lambda will re-use the instance for subsequent requests.

The handleRequest method of the class can use the handler object we declared in the previous step to send requests to the Spring application.

public class LambdaHandler implements RequestHandler<AwsProxyRequest, AwsProxyResponse> {
    static SpringLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler =
            SpringLambdaContainerHandler.getAwsProxyHandler(TestApp.class);

    public AwsProxyResponse handleRequest(AwsProxyRequest awsProxyRequest, Context context) {
        return handler.proxy(awsProxyRequest, context);
    }
}

Publish your Lambda function

You can follow the instructions in AWS Lambda's documentation on how to package your function for deployment.

Clone this wiki locally