java - AWS Lambda + Spring,如何加载application.yml

标签 java spring amazon-web-services aws-lambda microservices

我在为部署在 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/

相关文章:

java - onActivityResult 有效!但我无法调试

java - 如何从 Java 发送短信?

java - 运行spring应用程序时PropertyAccessorFactory NoClassDefFoundError

java - Spring Security 总是重定向到登录页面

未加密的 Amazon RDS 上的 Mysqldump 正在创建加密的 .db 文件

java - 在 jsf 中使用 ArrayDataModel 向数据表添加一行?

java - 使用 PDFBox 2.0 渲染 PDF 并解密

java - 在不加载 Spring 上下文的情况下测试 @ConfigurationProperties 注释

amazon-web-services - 如何使用 pyspark 从 s3 存储桶中读取 csv 文件

amazon-web-services - `Authorization Token has expired` 在 MacOS Sierra 上发出 AWS-CLI