0

I'm trying to do field-level injection so I don't have to pass "models" when my controllers are instantiated, like,

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

However my application throws NullPointerException, here 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?

quarks
  • 33,478
  • 73
  • 290
  • 513
  • 1
    Are you sure you are properly injecting you deps? If you use new UserController(), then that's your problem, you should use `injector.getInstance(UserController.class);`. – Guillaume Polet May 02 '12 at 13:02
  • I see, so the field-injection is ok? I mean, if I use getInstance method the UserModel will not be null? – quarks May 02 '12 at 16:56
  • Yes, using getInstance(UserController.class) all injectable fields will be injected. Just note that in the constructor, the fields are not injected yet, but after they are. If you need some values in the constructor, the only way around is to add those as injectable parameters of your constructor – Guillaume Polet May 02 '12 at 16:59

2 Answers2

1

Use In Guice

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

Use 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.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • I'm using Guice adaptation for GWT which is GIN so I think I can't call injector.getIntance though – quarks May 02 '12 at 17:47
  • @xybrek I think then that you should simply declare a method `public UserController getUserController()` on you interface extends Ginjector and it will do the rest. Then to get your controller, simply call `injector.getUserController()` – Guillaume Polet May 02 '12 at 17:59
  • @downvoter care to explain why the downvote? especially on an answer provided over 6 months ago? – Guillaume Polet Feb 11 '13 at 09:21
0

Your model field will be null while constructor is still running. It will be injected by GIN after the moment when UserController object is fully created. Here GWT GIN Field Level Injection you can find nice explanation about it.

Community
  • 1
  • 1
hsestupin
  • 1,115
  • 10
  • 19