问题
when code is executed in amazon aws lambda, my @autowired spring dependencies are null. Makes sense if there is no context being loaded, but i thought SpringBeanAutowiringSupport would help. How do you inject dependencies correctly in amazon lambda?
This is my code that has null autowired fields but otherwise works fine (if i replace autowired with new:
@Component
public class ApplicationEventHandler {
@Autowired
private Foo foo;
public ApplicationEventHandler() {
logger.info("I'm sure the constructor is being called");
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
//doesn't seem to help
}
public void deliveryFailedPermanentlyHandler(SNSEvent event, Context context) throws IOException {
foo.doStuff() // causes NPE
}
thanks in advance!
回答1:
this project on github provides a template for what i'm trying to do which works fine:
https://github.com/cagataygurturk/aws-lambda-java-boilerplate
回答2:
AWS Lambda Best Practices notes talks about DI:
Minimize the complexity of your dependencies. Prefer simpler frameworks that load quickly on Execution Context startup. For example, prefer simpler Java dependency injection (IoC) frameworks like Dagger or Guice, over more complex ones like Spring Framework.
So I'd like to suggest you to use Dagger 2 (because Square's Dagger 1.x is already deprecated). It provides such benefits:
- light-weight framework with very few integrations, Java interface/annotation configuration and compile-time code generated bindings;
- very small size;
- fail as early as possible ( compile-time, not runtime);
- performance - as fast as hand-written code and no coding around the framework.
来源:https://stackoverflow.com/questions/35753573/amazon-aws-lamba-function-with-spring-autowired-dependencies