如何将依赖项打入JAR?Java Maven项目部署AWS无服务器函数需求
Hey there! As a Java beginner working with AWS Serverless, you’re totally right—AWS Lambda can’t automatically pull in external dependencies like Gson, so you need a "fat JAR" (one that bundles all required libraries) to make your function work. Here are two reliable Maven solutions to get this done:
1. Use the Maven Shade Plugin
This is one of the most popular tools for building fat JARs, and it handles common issues like merging duplicate files from dependencies smoothly.
Add this configuration to your pom.xml inside the <build><plugins> section:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.4.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <!-- Optional: If your project has a main class, specify it here --> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>com.yourpackage.YourMainClass</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin>
Then run this command to build your fat JAR:
mvn clean package
Look in your target directory—shaded JAR won’t have -original in its name (that’s the slim, dependency-free version).
2. Use the Maven Assembly Plugin
This plugin lets you create a custom assembly of your project, including all dependencies in a single JAR.
Add this configuration to your pom.xml inside <build><plugins>:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.6.0</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <!-- Optional: Specify main class if needed --> <archive> <manifest> <mainClass>com.yourpackage.YourMainClass</mainClass> </manifest> </archive> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin>
Build with this command:
mvn clean package
Your fat JAR will be in the target directory, named something like your-project-name-1.0-SNAPSHOT-jar-with-dependencies.jar.
Quick Check to Ensure Gson is Included
To confirm Gson is bundled in your JAR, run this command:
jar tf target/your-fat-jar-name.jar | grep gson
You should see output like com/google/gson/Gson.class and other Gson-related files—this means the dependency is correctly included.
For AWS Lambda, just upload this fat JAR, and double-check your handler path (e.g., com.yourpackage.YourHandler::handleRequest) is properly configured in the Lambda console.
内容的提问来源于stack exchange,提问作者ken

