I am trying to learn Guice and I have a question on how to correctly wire up things. I am trying to get the call in BoofPanels doSomething() method to automatically use the MockFooImpl, but I don’t think things are wired properly.
In my case I have:
@ImplementedBy(MockFooImpl.class)
public interface FooInterface {
public int getBar(String one, String two);
}
@Singleton
public final class MockFooImpl implements FooInterface {
@Inject
public MockFooImpl() {
}
@Override
public int getBar(String one, String two) {
return 1;
}
}
public class Baz extends JFrame {
private BoofPanel boofPanel;
public Baz(String one, String two, Injector injector){
// Constructor with args
boofPanel = new BoofPanel("aString", 565);
injector.injectMembers(boofPanel);
}
public static void main(String[] args){
final Injector injector = Guice.createInjector();
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final Baz baz = new Baz("one","two", injector);
baz.setVisible(true);
}
});
}
}
public class BoofPanel extends JPanel {
@Inject
private FooInterface fooI;
public BoofPanel(String aString, int anInt){
}
public void doSomething(){
fooI.getBar();
}
}
Any help would be appreciated.
Thanks!
Guice isn’t magic. It will only inject into an object if either it creates it, or you ask it to. If you’re creating your own BoofPanel, then you’ll need to ask Guice to inject it. Add a constructor to Baz that looks like:
The BoofPanel constructor doesn’t need to do anything to the fooI variable; it can leave it null. You’ll also need to make main’s injector variable final, so the anonymous class created in main can capture it and pass it into the Baz constructor.
If you’d rather have BoofPanel created by Guice, then you’ll need to supply all the constructor parameters it needs to Guice, and call injectMembers on Baz itself.
EDIT: Specific changes to the code above, after edits.
Add a
finalto this declaration, to make it usable inside the anonymous inner class:final Injector injector = Guice.createInjector();Remove this line, as it’s unnecessary:
injector.getInstance(MockFooImpl.class);Add the injector to the invocation of the Baz constructor, to get it to where BoofPanel is created (i’ve also removed the unnecessary
finalhere):Baz baz = new Baz("one", "two", injector);Add the injector to the declaration of the Baz constructor, to receive it from the main method:
public Baz(String one, String two, Injector injector) {Add an injection into boofPanel to the Baz constructor, right after the
new BoofPanelline, to get Guice to inject BoofPanel:injector.injectMembers(boofPanel);That’s it.