我已将一个简单的 Spring Boot 项目上传到 Amazon Lambda,目前正在尝试测试它。
它可以 100% 工作,但当我尝试注入 Spring Bean 时,我得到一个空指针
这是我的 LambdaHandler 代码
package com.test.services.lambda;
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.test.services.MyServices;
public class MyLambdaFunctionHandler implements RequestHandler<String, String> {
public MyLambdaFunctionHandler() {
}
@Autowired
private ApplicationContext springContext;
private MyServices myServices;
public String handleRequest(String input, Context lambdaContext) {
this.myServices = springContext.getBean(MyServices.class);
lambdaContext.getLogger().log("AWS Request ID: " + lambdaContext.getAwsRequestId());
lambdaContext.getLogger().log("Input: " + input + " at " + Calendar.getInstance().getTimeInMillis());
myServices.sendGoodMessage("Message sent from Lambda");
return "Hello World";
}
}
我将 Amazon Lambda 中的处理程序设置为以下内容
com.test.services.lambda.MyLambdaFunctionHandler::handleRequest
但是,当我测试此功能时 - 我收到此错误消息
{
"errorMessage": "java.lang.NullPointerException",
"errorType": "java.lang.NullPointerException",
"stackTrace": [
"com.test.services.lambda.MyLambdaFunctionHandler.handleRequest(SlackLambdaFunctionHandler.java:23)",
"com.test.services.lambda.MyLambdaFunctionHandler.handleRequest(SlackLambdaFunctionHandler.java:12)"
]
}
我注入 Spring Bean 的地方失败了
任何人都可以提供有关如何将 spring bean 注入我的 AWS Lambda 处理程序的建议吗?
任何对此的帮助将不胜感激
谢谢
达米安
注入的方式有以下几种ApplicationContext
.
只要春天管理你的豆子,你的豆子就应该工作。你声明了吗MyLambdaFunctionHandler
在一些@Configuration
文件为@Bean
?
你用过吗new MyLambdaFunctionHandler()
在 spring 之外的地方初始化它@Configuration
? (这意味着 spring 没有管理你的 bean)。
如果 spring 不管理你的 bean,它就无法将 bean 注入其中。
如果没有,则应注释为@Component
并被一些人扫描@ComponentScan
.
如果声明了,则应该使用 springApplicationContextAware
设置你的ApplicationContext
。 Spring 有很多实用程序接口来将其一些核心类注入到您的 bean 中。
example:
public class MyLambdaFunctionHandler implements RequestHandler<String, String>, ApplicationContextAware {
public MyLambdaFunctionHandler() {
}
private ApplicationContext springContext;
private MyServices myServices;
public String handleRequest(String input, Context lambdaContext) {
this.myServices = springContext.getBean(MyServices.class);
lambdaContext.getLogger().log("AWS Request ID: " + lambdaContext.getAwsRequestId());
lambdaContext.getLogger().log("Input: " + input + " at " + Calendar.getInstance().getTimeInMillis());
myServices.sendGoodMessage("Message sent from Lambda");
return "Hello World";
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.springContext = applicationContext;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)