6

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?

asked Dec 21, 2017 at 9:35

2 Answers 2

5

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.

answered Feb 15, 2018 at 2:08
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer! I'd also add that a lambda should be a fairly small and self contained artifact. If you are instantiating a large object hierarchy, you are probably doing too much in a single lambda.
0

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

answered Feb 9, 2018 at 23:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.