質問

I have a good understanding of mvc. What Im still unsure about is how to properly use google guice to inject dependencies. Here is part of my code:

protected void configure() {
    bind(IAppController.class).to(AppController.class);
    bind(IAppView.class).to(AppView.class);
    bind(IAppModel.class).to(AppModel.class);
}

Now, I am unsure how to inject the dependencies properly. I would like to ask your opinion on the best way to handle this. I Inject them in the constructors like this

public class AppController implements IAppController {

private IAppView appView;
private IAppModel appModel;

@Inject
public AppController(IAppView appView, IAppModel appModel){
    this.appModel = appModel;
    this.appView = appView;
}

}

Now the example above works but adds another problem. How can i give the model an instance of the view? My view is the observer and i need the same instance of the injected view in the controller to be injected in the model. Another approach I came up with is to simply use the injector to get instances of the model, view, controller and assemble them there? such as:

public static void main(String[] args){
    Injector injector = Guice.createInjector(new AppBootstrapLoader());
    IAppController controller = injector.getInstance(IAppController.class);
    IAppView view =...
    IAppModel model =....
    controller.setModel(model);
    controller.setView(view);
    model.addObserver(view);
}

My last approach would be to have the model view and controller as singletons so I would be sure that all injected instances are the same. Im still new to guice and I still cant comprehend how it handles dependencies. I also want to do this cleanly and thus I am researching. I would like to hear your experiences and opinions on this manner. Thank you.

役に立ちましたか?

解決

I think what you're looking for is "method injection." Note that the binding process will fail if the given dependency dose not exist.

Method Injection:

@Inject
public void setView(View view) {
    this.view = view;
}

You could also use field injection. But I'm not really a fan of it because it makes writing unit tests harder if you can only set the dependency through reflection.

Field Injection:

@Inject
private View view

source: injections

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top