我在为部署在 AWS lambda 上的 Restful 应用程序自定义 API 网关域时遇到问题。自定义域以这种方式工作,根据basePath选择不同的API,最终触及Lambda。例如:
api.mycustomdomain.com/view/ping
-> 使用路径 /view/ping
转到应用程序 view
api.mycustomdomain.com/admin/ping
-> 转到应用程序admin
,路径为/admin/ping
我使用此示例作为样板:https://github.com/awslabs/aws-serverless-java-container/tree/master/samples/spring/pet-store
我想要实现的是处理程序,它依赖于 Host
header 从请求路径中去除前缀。
我准备了以下 application.yml 文件:
server:
contextPath: "/view"
productionHost: "api.mycustomdomain.com"
问题是。我现在如何将它们加载到我的 Lambda 函数中?这是我天真的尝试:
public class LambdaHandler implements RequestHandler<AwsProxyRequest, AwsProxyResponse> {
SpringLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
boolean isinitialized = false;
@Value("${server.contextPath}")
private String prefix;
@Value("${server.productionHost}")
private String productionHost;
public AwsProxyResponse handleRequest(AwsProxyRequest awsProxyRequest, Context context) {
if(awsProxyRequest.getHeaders().get("Host").equals(productionHost))
awsProxyRequest.setPath(awsProxyRequest.getPath().substring(prefix.length()));
if (!isinitialized) {
isinitialized = true;
try {
handler = SpringLambdaContainerHandler.getAwsProxyHandler(PingPongApp.class);
} catch (ContainerInitializationException e) {
e.printStackTrace();
return null;
}
}
return handler.proxy(awsProxyRequest, context);
}
}
显然这不起作用,LambdaHandler 是在 Spring 上下文之外工作的。
有什么想法可以解决这个问题吗?
最佳答案
您似乎无法加载这些属性。请遵循下面给出的 2 个选项之一。
1> 您可以在配置中添加以下 bean,这样您就可以 Autowiring 字符串并使用您已经使用的方式
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
2>
public AwsProxyResponse..{
@Autowired
private Environment env;
..
public AwsProxyResponse handleRequest{
..
String contextPath = env.getRequiredProperty(“server.contextPath”));
...
}
}
关于java - AWS Lambda + Spring,如何加载application.yml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43018514/