添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

AWS Lambda Java: How to create your first AWS Lambda Function in Java

In this tutorial, I'll show you how to create a simple AWS Lambda function using Java. We'll start with a plain Java project, upload it to the AWS console, and test it. Along the way, I'll share some of the pain points I encountered while building serverless functions, and in a later tutorial you will see how you can overcome them using tools like Spring Cloud Function.

Getting Started

First, create a new Java project using your favorite IDE or text editor. I'll be using IntelliJ IDEA Ultimate Edition, but you can also use the Community Edition or another tool of your choice.

Create a new Maven project and choose the quickstart archetype, which gives us a basic shell of an application. We'll be using Java 11 and JUnit 5.8.2 for our project.

Maven QuickStart Archetype

To start, let's create a simple Java class that will hold our Lambda function. Name the class HelloLambda , and create a method called handleRequest that returns a String .

public class HelloLambda {
    public String handleRequest() {
        return "Hello, AWS Lambda!";

This is a very simple function that just takes a name as input and returns a greeting message. Now, let's create a test for our function using JUnit.

Writing Tests

It's always a good practice to write tests for your functions. Create a new test class called HelloLambdaTest and add a method named shouldReturnHelloMessage .

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class HelloLambdaTest {
    @Test
    void shouldReturnHelloMessage() {
        var sut = new HelloLambda();
        assertEquals("Hello, AWS Lambda!",sut.handleRequest());

Run the test to make sure it passes. Now that we have our function and test, we need to package the function using the Maven Shade Plugin.

Maven Shade Plugin

The Maven Shade Plugin is responsible for packaging the project classes together with their dependencies into a single "Uber JAR". This is what AWS Lambda expects when we upload our function.

To configure the Maven Shade Plugin, add a build section containing the plugin configuration to the pom.xml file:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.2.4</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <shadedArtifactAttached>true</shadedArtifactAttached>
                        <shadedClassifierName>aws-lambda</shadedClassifierName>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>