Field Level Implementation with Gin

I'm trying to do an injection at the field level, so I don’t need to pass “models” when my controllers are created, for example

UserController controller = new UserController(/*No need to pass models here*/);

However, my application raises a NullPointerException, here is my code:

UserController.java

    public class UserController implements Controller {
        @Inject private UserModel model;
        public UserController() {
          model.doSomething(); // NullPointerException
        }
    }

ClientGinModule.java

public class ClientGinModule extends AbstractGinModule {
    @Override
    protected void configure() {
        bind(UserModel.class).in(Singleton.class);
    }
}

What could be the problem?

0
source share
2 answers

Usage in Guice

UserController controller = injector.getInstance(UserController.class);

Usage in Gin:

// Declare a method returning a UserController on your interface extending Ginjector
public UserController getUserController();

// When you need the controller, just call:
injector.getUserController();

to get a fully injected controller.

+1
source

The field modelwill be empty while the constructor is still running. It will be entered by the GIN after the moment the object is created UserController. Here GWT GIN Field Level Injection you can find a good explanation.

0

All Articles