Google Guice Integration in AWS Lambda

I am trying to integrate Google Guice into AWS Lambda, but for some reason the injection does not work. He gives me null when I try to call

Handler Code:

public class FirstLamdba implements RequestHandler<Request, Object>{   

        private UserService userService;

        @Inject
        public void seUserService(UserService userService) {
            this.userService = userService;
        }

        public Object handleRequest(Request request, Context context){

            userService.persistData();
}

User service

public interface UserService {
    List<String> persistData();
}

UserServiceImpl

public class UserServiceImpl implements UserService{


    @Override
    public List<String> persistData() {

        System.out.println("***Working*********");
}

Binding Class:

public class MessageGuiceModule extends AbstractModule
{
  protected void configure() {

    bind(UserService.class).to(UserServiceImpl.class);
  }
}

Testing Class:

 @Test
        public void testLambdaFunctionHandler() {
Request request = new Request();
            request.setName("Name");
            FirstLamdba handler = new FirstLamdba();
            Context ctx = createContext();

            Object output = handler.handleRequest(request, ctx);

            // TODO: validate output here if needed.
            if (output != null) {
                System.out.println(output.toString());
            }
        }

For some reason, the UserService userService sets NULL to FirstLamdba.

Any idea?

+4
source share
2 answers

The first time you call the lambda function, an environment is created.

public class FirstLamdba implements RequestHandler<Request, Object>{   

        Injector injector = Guice.createInjector(new MessageGuiceModule());
        private UserService userService = injector.getInstance(UserService.class);


        //setter for testing purpose
        public void setUserService(UserService userService) {
            this.userService = userService;
        }

        public Object handleRequest(Request request, Context context){

            userService.persistData();
}


@Test
public void testLambdaFunctionHandler() {
        Request request = new Request();
        request.setName("Name");
        FirstLamdba handler = new FirstLamdba();
        handler.setUserService(mockUserService);

        Context ctx = createContext();

        Object output = handler.handleRequest(request, ctx);

        // TODO: validate output here if needed.
        if (output != null) {
            System.out.println(output.toString());
        }
}
+2
source

Lambda RequestHandler Guice, @Inject RequestHandler . userService null.

Guice Lambda, , Guice.createInjector() - , Guice.

, AWS Lambda POJO, , , , persistUser(), Lambda. , Lambda , POJO persistUser().

+1

Source: https://habr.com/ru/post/1659278/


All Articles