I am new to AWS Lambda. If I use Spring dependency injection framework in my Java Lambda function, how and when does the Spring application context get initialized?
2 Answers 2
Using a Spring injection framework is fairly heavy-weight, and probably not the best for a lambda. (Edit: per Jeff's comment, lambdas should be fairly small and self-contained artifacts-- if you're starting to find yourself with a large object hierarchy, consider multiple lambdas or whether a lambda solution makes the most sense for your service).
To your question, the application context would get initialized just like a traditional service when the lambda is first invoked, and can be stored locally and reused. However, depending on how often you're invoking your lambda, this reuse is not guaranteed, and the components may end up being reinitialized often. Basically, using Spring can keep you from getting the full benefit of using lambdas.
As an alternative, AWS recommends using more lightweight frameworks, like Dagger or Guice, in their best practices.
1 Comment
AWS lambda request handlers are not Spring components and I don't think there's an easy way to componentize them which makes DI a problem. There's multiple ways getting around this issue but I've found the solution described in the following post the least "magical": Just Spring-enabled AWS Lambdas