如何在无Event对象的AWS Lambda POJO处理器中获取路径参数?
Got it! I've run into this exact issue before—when you're using a POJO to directly deserialize the request body, path parameters and other request metadata don't get automatically passed into that model. Let's break down solutions based on common frameworks/runtimes you're likely using:
Scenario 1: AWS Lambda + API Gateway
In this setup, Lambda defaults to deserializing only the request body into your MyCustomModel, so path parameters are excluded by default. Here are two solid approaches:
Approach A: Create a wrapper class for full request context
Define a new class that wraps both your request body model and path parameters, then have Lambda deserialize the entire API Gateway request into this class:
public class ApiGatewayRequestWrapper { private MyCustomModel body; private Map<String, String> pathParameters; // Add getters and setters (or use Lombok's @Data for brevity) public MyCustomModel getBody() { return body; } public void setBody(MyCustomModel body) { this.body = body; } public Map<String, String> getPathParameters() { return pathParameters; } public void setPathParameters(Map<String, String> pathParameters) { this.pathParameters = pathParameters; } }
Update your handler method to accept this wrapper:
@Override public Object handleRequest(ApiGatewayRequestWrapper request, Context context) { MyCustomModel model = request.getBody(); String id = request.getPathParameters().get("id"); // Grab your path parameter // Your processing logic here }
Critical Configuration: In API Gateway's Integration Request, set up a VTL mapping template to convert the full request data into the wrapper structure:
{ "body": $input.json('$'), "pathParameters": $input.params().path }
Approach B: Fetch context via reflection (not recommended)
Some Lambda runtimes let you access request metadata through the Context object via reflection, but this is fragile and not portable across environments. Avoid this for production code.
Scenario 2: Spring Boot/Spring Cloud Function
Spring makes this straightforward—just add a @PathVariable parameter alongside your request body POJO:
@Override public Object handleRequest(@RequestBody MyCustomModel model, @PathVariable("id") String id, Context context) { // Use both the deserialized model and path parameter directly }
Make sure your route configuration defines the path /some/path/{id}; Spring will automatically inject the id value from the URL.
Scenario 3: Other Java Web Frameworks (Quarkus, Micronaut)
The pattern is similar to Spring—use the framework's built-in annotation for path parameters alongside your request body POJO:
- For Quarkus/RESTEasy: Use
@PathParam("id") String id - For Micronaut: Use
@PathVariable String id
Add these annotations to your handler method parameters, and the framework will inject both the request body model and path parameter.
内容的提问来源于stack exchange,提问作者Dreadhawk177

