'Not able to inject dependencies inside the AWS Lambda function through Springs framework

I am trying to create a SQS poller inside the AWS Lambda, and I am trying to process the messages fetched from the SQS queue. In this code I am using Spring Framework to inject the dependencies, so for now I am not using Guice or Dagger or creating objects using "new" operator.

But when I declare all the beans in the ApplicationBeans.java file inside the spring folder, none of my beans gets initialized.

My ApplicationBeans.java looks like this:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class ApplicationBeans
{

@Bean
-----------
-----------
----------
}

And my main class where I need to inject the dependencies looks like these:

import lombok.AllArgsConstructor;
@AllArgsConstructor
public class MainClass implements RequestHandler<SQSEvent, Void>
{
private Dependency1 dependency1;
-----
-----
-----

}

But now when I try to access the dependency1 in the code, it gives me a nullPointer exception. What is going wrong in configuring Springs in AWS Lambda?



Solution 1:[1]

In your code here, you have to specify annotations such as

@Autowired

or

@Resource

so that spring realizes to inject bean to it.

import lombok.AllArgsConstructor;
@AllArgsConstructor
public class MainClass implements RequestHandler<SQSEvent, Void>
{
    @Autowired
    private Dependency1 dependency1;
    -----
    -----
    -----
}

If you are not willing to use annotations, then you have to use ApplicationContext class to get the Beans using getBean() method.

Hope this helps!!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Himanshu Jain