

# Setting up the AWS SDK for Java 2.x
<a name="setup"></a>

This section provides information about how to set up your development environment and projects to use the AWS SDK for Java 2.x.

## Setup overview
<a name="setup-overview"></a>

To successfully develop applications that access AWS services using the AWS SDK for Java, the following conditions are required:
+ The Java SDK must have access to credentials to [authenticate requests](get-started-auth.md#setup-auth) on your behalf.
+ The [permissions of the IAM role](https://docs.aws.amazon.com/singlesignon/latest/userguide/permissionsetsconcept.html) configured for the SDK must allow access to the AWS services that your application requires. The permissions associated with the **PowerUserAccess** AWS managed policy are sufficient for most development needs.
+ A development environment with the following elements:
  + [Shared configuration files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) that are set up in at least one of the following ways:
    + The `config` file contains [IAM Identity Center single sign-on settings](get-started-auth.md#setup-credentials) so that the SDK can get AWS credentials.
    + The `credentials` file contains temporary credentials.
  + An [installation of Java 8](setup-java-buildtool.md) or later.
  + A [build automation tool ](setup-java-buildtool.md)such as [Maven](https://maven.apache.org/download.cgi) or [Gradle](https://gradle.org/install/).
  + A text editor to work with code.
  + (Optional, but recommended) An IDE (integrated development environment) such as [IntelliJ IDEA](https://www.jetbrains.com/idea/download/#section=windows), [Eclipse](https://www.eclipse.org/ide/), or [NetBeans](https://netbeans.apache.org/front/main/download/index.html).

    If you use IntelliJ IDEA, you can also add the [AWS Toolkit for IntelliJ IDEA](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) to integrate AWS services directly into the IDE to help you streamline development.
+ An active AWS access portal session when you are ready to run your application. You use the AWS Command Line Interface to [initiate the sign-in process](get-started-auth.md#setup-login-sso) to IAM Identity Center's AWS access portal.

**Important**  
The instructions in this setup section assume that you or organization uses IAM Identity Center. If your organization uses an external identity provider that works independently of IAM Identity Center, find out how you can get temporary credentials for the SDK for Java to use. Follow [these instructions](credentials-temporary.md#credentials-temporary-from-portal) to add temporary credentials to the `~/.aws/credentials` file.  
If your identity provider adds temporary credentials automatically to the `~/.aws/credentials` file, make sure that the profile name is `[default]` so that you do not need to provide a profile name to the SDK or AWS CLI.

# Install Java and a build tool to work with the AWS SDK for Java 2.x
<a name="setup-java-buildtool"></a>

You need the following Java development environment requirements to work with SDK for Java 2.x:
+ Java 8 or later. The AWS SDK for Java works with the [Oracle Java SE Development Kit](https://www.oracle.com/java/technologies/downloads/) and with distributions of Open Java Development Kit (OpenJDK) such as [Amazon Corretto](https://aws.amazon.com/corretto/), [Red Hat OpenJDK](https://developers.redhat.com/products/openjdk/overview), and [Adoptium](https://adoptium.net/).
+ A Maven-compatible build tools such as Apache Maven, Apache Ant with Ivy, Gradle, or IntelliJ.
  + For information about how to install and use Maven, see [https://maven.apache.org/](https://maven.apache.org/).
  + For information about how to install and use Apache Ivy, see [https://ant.apache.org/ivy/](https://ant.apache.org/ivy/).
  + For information about how to install and use Gradle, see [https://gradle.org/](https://gradle.org/).
  + For information about how to install and use IntelliJ IDEA, see [https://www.jetbrains.com/idea/](https://www.jetbrains.com/idea/).

# Set up an Apache Maven project that uses the AWS SDK for Java 2.x
<a name="setup-project-maven"></a>

You can use [Apache Maven](https://maven.apache.org/) to set up and build AWS SDK for Java 2.x projects, or to [build the SDK itself](https://github.com/aws/aws-sdk-java-v2/tree/master#building-from-source).

## Prerequisites
<a name="prerequisitesmaven"></a>

To use the SDK for Java 2.x with Maven, you need the following:
+ Java *8.0 or later*. You can download the latest Java SE Development Kit software from [http://www.oracle.com/technetwork/java/javase/downloads/](https://www.oracle.com/java/technologies/downloads/). The SDK for Java 2.x also works with [OpenJDK](https://openjdk.org/) and Amazon Corretto, a distribution of the Open Java Development Kit (OpenJDK). Download the latest OpenJDK version from [https://openjdk.java.net/install/index.html](https://openjdk.org/install/index.html). Download the latest Amazon Corretto 8 or Amazon Corretto 11 version from [the Corretto page](https://aws.amazon.com/corretto/).
+  *Apache Maven*. If you need to install Maven, go to [http://maven.apache.org/](https://maven.apache.org/) to download and install it.

## Create a Maven project
<a name="create-maven-project"></a>

To create a Maven project from the command line, run the following command from a terminal or command prompt window````.

```
mvn -B archetype:generate \
 -DarchetypeGroupId=software.amazon.awssdk \
 -DarchetypeArtifactId=archetype-lambda -Dservice=s3 -Dregion=US_WEST_2 \
 -DarchetypeVersion=2.X.X \
 -DgroupId=com.example.myapp \
 -DartifactId=myapp
```

**Note**  
Replace *com.example.myapp* with the full package namespace of your application. Also replace *myapp* with your project name. This becomes the name of the directory for your project.  
To use the latest version of the archetype, replace *2.X.X* with the [latest from Maven central](https://central.sonatype.com/artifact/software.amazon.awssdk/archetype-lambda).

This command creates a Maven project using the archetype templating toolkit. The archetype generates the scaffolding for an AWS Lambda function handler project . This project archetype is preconfigured to compile with Java SE 8 and includes a dependency to the version of the SDK for Java 2.x specified with `-DarchetypeVersion`.

For more information about creating and configuring Maven projects, see the [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/).

## Configure the Java compiler for Maven
<a name="configure-maven-compiler"></a>

If you created your project using the AWS Lambda project archetype as described previously, the configuration of the Java compiler is already done for you.

To verify that this configuration is present, start by opening the `pom.xml` file from the project folder you created (for example, `myapp`) when you executed the previous command. Look on lines 11 and 12 to see the Java compiler version setting for this Maven project, and the required inclusion of the Maven compiler plugin on lines 71-75.

```
<project>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven.compiler.plugin.version}</version>
      </plugin>
    </plugins>
  </build>
</project>
```

If you create your project with a different archetype or by using another method, you must ensure that the Maven compiler plugin is part of the build and that its source and target properties are both set to **1.8** in the `pom.xml` file.

See the previous snippet for one way to configure these required settings.

Alternatively, you can configure the compiler configuration inline with the plugin declaration, as follows.

```
<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
```

## Declare the SDK as a dependency
<a name="sdk-as-dependency"></a>

To use the AWS SDK for Java in your project, you need to declare it as a dependency in your project’s `pom.xml` file.

If you created your project using the project archetype as described previously, the latest version of the SDK is already configured as a dependency in your project. 

The archetype generates a BOM (bill of materials) artifact dependency for the `software.amazon.awssdk` group id. With a BOM, you do not have to specify the maven version for individual artifact dependencies that share the same group id.

If you created your Maven project in a different way, configure the latest version of the SDK for your project by ensuring that the `pom.xml` file contains the following.

```
<project>
  <properties>
    <aws.java.sdk.version>2.X.X</aws.java.sdk.version>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>bom</artifactId>
        <version>${aws.java.sdk.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>
```

**Note**  
Replace *2.X.X* in the `pom.xml` file with the [latest version of the AWS SDK for Java 2.x](https://central.sonatype.com/artifact/software.amazon.awssdk/bom).

## Set dependencies for SDK modules
<a name="modules-dependencies"></a>

Now that you have configured the SDK, you can add dependencies for one or more of the AWS SDK for Java modules to use in your project.

Although you can specify the version number for each component, you don’t need to because you already declared the SDK version in the `dependencyManagement` section using the bill of materials artifact. To load a different version of a given module, specify a version number for its dependency.

If you created your project using the project archetype as described previously, your project is already configured with multiple dependencies. These include dependences for AWS Lambda function handlers and Amazon S3, as follows.

```
<project>
    <dependencies>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>s3</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>software.amazon.awssdk</groupId>
                    <artifactId>netty-nio-client</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>software.amazon.awssdk</groupId>
                    <artifactId>apache-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>url-connection-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-core</artifactId>
            <version>${aws.lambda.java.version}</version>
        </dependency>
    </dependencies>
</project>
```

**Note**  
In the `pom.xml` example above, the dependencies are from different `groupId`s. The `s3` dependency is from `software.amazon.awssdk`, whereas the `aws-lambda-java-core` dependency is from `com.amazonaws`. The BOM dependency management configuration affects artifacts for `software.amazon.awssdk`, so a version is needed for the `aws-lambda-java-core` artifact.  
For the development of *Lambda function handlers* using the SDK for Java 2.x, `aws-lambda-java-core` is the correct dependency. However, if your application needs to manage Lambda resources, using operations such as `listFunctions`, `deleteFunction`, `invokeFunction`, and `createFunction`, your application requires the following dependency.   

```
<groupId>software.amazon.awssdk</groupId>
<artifactId>lambda</artifactId>
```

**Note**  
The `s3` dependency excludes the the `netty-nio-client` and `apache-client` transitive dependencies. In place of either of those HTTP clients, the archetype includes the `url-connection-client` dependency, which helps [reduce the startup latency for AWS Lambda functions](lambda-optimize-starttime.md#lambda-quick-url).

Add the modules to your project for the AWS service and features you need for your project. The modules (dependencies) that are managed by the AWS SDK for Java BOM are listed on the [Maven central repository](https://central.sonatype.com/artifact/software.amazon.awssdk/bom).

**Note**  
You can look at the `pom.xml` file from a code example to determine which dependencies you need for your project. For example, if you’re interested in the dependencies for the DynamoDB service, see [this example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/da520cb4436f8567a90b6f73f77232fd590a50bf/javav2/example_code/dynamodb/pom.xml) from the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2) on GitHub. (Look for the `pom.xml` file under [/javav2/example\$1code/dynamodb](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb).)

### Build the entire SDK into your project
<a name="build-the-entire-sdk-into-your-project"></a>

To optimize your application, we strongly recommend that you pull in only the components you need instead of the entire SDK. However, to build the entire AWS SDK for Java into your project, declare it in your `pom.xml` file, as follows.

```
<project>
  <dependencies>
    <dependency>
      <groupId>software.amazon.awssdk</groupId>
      <artifactId>aws-sdk-java</artifactId>
      <version>2.X.X</version>
    </dependency>
  </dependencies>
</project>
```

## Build your project
<a name="build-project"></a>

After you configure the `pom.xml` file, you can use Maven to build your project.

To build your Maven project from the command line, open a terminal or command prompt window, navigate to your project directory (for example, `myapp`), enter or paste the following command, then press Enter or Return.

```
mvn package
```

This creates a single `.jar` file (JAR) in the `target` directory (for example, `myapp/target`). This JAR contains all of the SDK modules you specified as dependencies in your `pom.xml` file.

# Set up a Gradle project that uses the AWS SDK for Java 2.x
<a name="setup-project-gradle"></a>

You can use [Gradle](https://gradle.org/) to set up and build AWS SDK for Java 2.x projects. 

The initial steps in the following example come from [Gradle's Getting Started guide](https://docs.gradle.org/current/samples/sample_building_java_applications.html) for version 8.4. If you use a different version, your results may differ slightly.

**To create a Java application with Gradle (command line)**

1. Create a directory to hold your project. In this example, `demo` is the directory name.

1. Inside the `demo` directory, execute the `gradle init` command and supply the values highlighted in red as shown in the following command line output. For the walk through, we choose Kotlin as the build script DSL language, but a complete example for Groovy is also shown at the end of this topic.

   ```
   > gradle init
   Starting a Gradle Daemon (subsequent builds will be faster)
   
   Select type of project to generate:
   1: basic
   2: application
   3: library
   4: Gradle plugin
   Enter selection (default: basic) [1..4] 2
   
   Select implementation language:
   1: C++
   2: Groovy
   3: Java
   4: Kotlin
   5: Scala
   6: Swift
   Enter selection (default: Java) [1..6] 3
   
   Generate multiple subprojects for application? (default: no) [yes, no] no
   Select build script DSL:
   1: Kotlin
   2: Groovy
   Enter selection (default: Kotlin) [1..2] <Enter>
   
   Select test framework:
   1: JUnit 4
   2: TestNG
   3: Spock
   4: JUnit Jupiter
   Enter selection (default: JUnit Jupiter) [1..4] 4
   
   Project name (default: demo): <Enter>
   Source package (default: demo): <Enter>
   Enter target version of Java (min. 7) (default: 11): <Enter>
   Generate build using new APIs and behavior (some features may change in the next minor release)? (default: no) [yes, no] <Enter>
   
   > Task :init
   To learn more about Gradle by exploring our Samples at https://docs.gradle.org/8.4/samples/sample_building_java_applications.html
   
   BUILD SUCCESSFUL in 3m 43s
   2 actionable tasks: 2 executed
   ```

1. After the `init` task completes, the `demo` directory contains the following tree structure. We take a closer look at the main build file, `build.gradle.kts` (highlighted in red), in the next section.

   ```
   ├── app
   │   ├── build.gradle.kts
   │   └── src
   │       ├── main
   │       │   ├── java
   │       │   │   └── demo
   │       │   │       └── App.java
   │       │   └── resources
   │       └── test
   │           ├── java
   │           │   └── demo
   │           │       └── AppTest.java
   │           └── resources
   ├── gradle
   │   └── wrapper
   │       ├── gradle-wrapper.jar
   │       └── gradle-wrapper.properties
   ├── gradlew
   ├── gradlew.bat
   └── settings.gradle.kts
   ```

   The `build.gradle.kts` file contains the following scaffolded content.

   ```
   /*
    * This file was generated by the Gradle 'init' task.
    *
    * This generated file contains a sample Java application project to get you started.
    * For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle documentation.
    */
   
   plugins {
       // Apply the application plugin to add support for building a CLI application in Java.
       application
   }
   
   repositories {
       // Use Maven Central for resolving dependencies.
       mavenCentral()
   }
   
   dependencies {
       // Use JUnit Jupiter for testing.
       testImplementation("org.junit.jupiter:junit-jupiter:5.9.3")
   
       testRuntimeOnly("org.junit.platform:junit-platform-launcher")
   
       // This dependency is used by the application.
       implementation("com.google.guava:guava:33.3.0-jre")
   }
   
   // Apply a specific Java toolchain to ease working on different environments.
   java {
       toolchain {
           languageVersion.set(JavaLanguageVersion.of(11))
       }
   }
   
   application {
       // Define the main class for the application.
       mainClass.set("demo.App")
   }
   
   tasks.named<Test>("test") {
       // Use JUnit Platform for unit tests.
       useJUnitPlatform()
   }
   ```

1. Use the scaffolded Gradle build file as the basis for your AWS project.

   1. To manage SDK dependencies for your Gradle project, add the Maven bill of materials (BOM) for the AWS SDK for Java 2.x to the `dependencies` section of the `build.gradle.kts` file.

      ```
      ...
      dependencies {
          implementation(platform("software.amazon.awssdk:bom:2.27.21"))
          // With the bom declared, you specify individual SDK dependencies without a version.
       ...
      }
      ...
      ```
**Note**  
In this example build file, replace *2.27.21* with the latest version of the SDK for Java 2.x. Find the latest version available in [Maven central repository](https://central.sonatype.com/artifact/software.amazon.awssdk/bom/versions).

   1. Specify the SDK modules your application needs in the `dependencies` section. As an example, the following adds a dependency on Amazon Simple Storage Service. 

      ```
      ...
      dependencies {    
          implementation(platform("software.amazon.awssdk:bom:2.27.21"))
          implementation("software.amazon.awssdk:s3")
       ...
      }
      ...
      ```

      Gradle automatically resolves the correct version of declared dependencies by using the information from the BOM.

The following examples show complete Gradle build files in both the Kotlin and Groovy DSLs. The build file contains dependencies for Amazon S3, authentication, logging, and testing. The source and target version of Java is version 11.

------
#### [ Kotlin DSL (build.gradle.kts) ]

```
/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java application project to get you started.
 * For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle documentation.
 */

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    application
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    implementation(platform("software.amazon.awssdk:bom:2.20.56"))
    implementation("software.amazon.awssdk:s3")
    implementation("software.amazon.awssdk:sso")
    implementation("software.amazon.awssdk:ssooidc")
    implementation(platform("org.apache.logging.log4j:log4j-bom:2.20.0"))
    implementation("org.apache.logging.log4j:log4j-slf4j2-impl")
    implementation("org.apache.logging.log4j:log4j-1.2-api")
    testImplementation(platform("org.junit:junit-bom:5.10.0"))
    testImplementation("org.junit.jupiter:junit-jupiter")
}

// Apply a specific Java toolchain to ease working on different environments.
java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(11))
    }
}

application {
    // Define the main class for the application.
    mainClass.set("demo.App")
}

tasks.named<Test>("test") {
    // Use JUnit Platform for unit tests.
    useJUnitPlatform()
}
```

------
#### [ Groovy DSL (build.gradle) ]

```
/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java application project to get you started.
 * For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle documentation.
 */

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    implementation platform('software.amazon.awssdk:bom:2.27.21')
    implementation 'software.amazon.awssdk:s3'
    implementation 'software.amazon.awssdk:sso'
    implementation 'software.amazon.awssdk:ssooidc'
    implementation platform('org.apache.logging.log4j:log4j-bom:2.20.0')
    implementation 'org.apache.logging.log4j:log4j-slf4j2-impl'
    implementation 'org.apache.logging.log4j:log4j-1.2-api'
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

// Apply a specific Java toolchain to ease working on different environments.
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(11)
    }
}

application {
    // Define the main class for the application.
    mainClass = 'demo_groovy.App'
}

tasks.named('test') {
    // Use JUnit Platform for unit tests.
    useJUnitPlatform()
}
```

------

For next steps, see the Getting Started guide on the Gradle website for instructions on how to [build and run a Gradle application](https://docs.gradle.org/current/samples/sample_building_java_applications.html#run_the_application).

# Set up a GraalVM Native Image project that uses the AWS SDK for Java 2.x
<a name="setup-project-graalvm"></a>

With versions 2.16.1 and later, the AWS SDK for Java 2.x provides out-of-the-box support for GraalVM Native Image applications. Use the `archetype-app-quickstart` Maven archetype to set up a project with built-in native image support.

## Prerequisites
<a name="setup-graalvmnativeimage-prereq"></a>
+ Complete the steps in [Setting up the AWS SDK for Java 2.x](setup.md).
+ Install [GraalVM Native Image](https://www.graalvm.org/reference-manual/native-image/#install-native-image).

## Create a project using the archetype
<a name="setup-graalvmnativeimage-project"></a>

To create a Maven project with built-in native image support, in a terminal or command prompt window, use the following command.

**Note**  
Replace `com.example.mynativeimageapp` with the full package namespace of your application. Also replace `mynativeimageapp` with your project name. This becomes the name of the directory for your project.

```
mvn archetype:generate \
    -DarchetypeGroupId=software.amazon.awssdk \
    -DarchetypeArtifactId=archetype-app-quickstart \
    -DarchetypeVersion=2.27.21\
    -DnativeImage=true \
    -DhttpClient=apache-client \
    -Dservice=s3 \
    -DgroupId=com.example.mynativeimageapp \
    -DartifactId=mynativeimageapp \
    -DinteractiveMode=false
```

This command creates a Maven project configured with dependencies for the AWS SDK for Java, Amazon S3, and the `ApacheHttpClient` HTTP client. It also includes a dependency for the [GraalVM Native Image Maven plugin](https://graalvm.github.io/native-build-tools/latest/index.html), so that you can build native images using Maven.

To include dependencies for a different Amazon Web Services, set the value of the `-Dservice` parameter to the artifact ID of that service. Examples include `dynamodb`, `comprehend`, and `pinpoint`. For a complete list of artifact IDs, see the list of managed dependencies for [software.amazon.awssdk on Maven Central](https://mvnrepository.com/artifact/software.amazon.awssdk/bom/latest).

To use an asynchronous HTTP client, set the `-DhttpClient` parameter to `netty-nio-client`. To use `UrlConnectionHttpClient` as the synchronous HTTP client instead of `apache-client`, set the `-DhttpClient` parameter to `url-connection-client`.

## Build a native image
<a name="build-graalvmnativeimage-project"></a>

After you create the project, run the following command from your project directory, for example, `mynativeimageapp`:

```
mvn package -P native-image
```

This creates a native image application in the `target` directory, for example, `target/mynativeimageapp`.