Vaadin with Guice newbie question

Hi
I am sure this is a dumb question, so apologies in advance…
Have followed the Vaadin Guice Integration article, so far so good


class MyServletConfig
{// etc

protected void configureServlets() {
                serve("/*").with(GuiceApplicationServlet.class);

                bind(Application.class).to(SimpleApp.class).in(ServletScopes.SESSION);
                bind(Foo.class).to(FooImpl.class);
 //               bindConstant().annotatedWith(Names.named("bar")).to("bar");
            }
}

public class SimpleApp extends Application {
	
	@Inject protected Foo foo;
	
	@Override
	public void init() {
		Window mainWindow = new Window(""+foo);
		setMainWindow(mainWindow);
	}
}

The above works (window title=“foo”)
But when I try to inject outside of this class (uncommenting the bar binding of course),


public class SimpleApp extends Application {
	
	@Inject protected Foo foo;
	
	@Override
	public void init() {
		Bar bar = new Bar();
		Window mainWindow = new Window(""+foo+" "+bar);
		setMainWindow(mainWindow);
	}
}

public class Bar
{
	@Inject @Named("bar") protected String text;
	
	public String toString()
	{
		return text;
	}
}

This doesnt work (window title=“foo null”)

Any suggestions
\Dave Mc

(I can’t help, but please use code tags :))

With my limited knowledge of Guice, the problem seems to be in line 2 here:

	public void init() {
		Bar bar = new Bar();
		Window mainWindow = new Window(""+foo+" "+bar);
		setMainWindow(mainWindow);
	}

Because bar is created in-place using constructor, Guice doesn’t have a chance to “kick in” and inject the properties inside Bar-class. This can easily be fixed by injecting also the bar-object using one of various methods that Guice offers.

One possibility:

Make this binding in configureServlets() -method:

bind(Bar.class);

And instead of calling the constructor, inject bar into SimpleApp:

public class SimpleApp extends Application {
    @Inject
    protected Bar bar;

    // ... the rest of the code, without bar = new Bar()
}