I have one Maven module where I define some utils shared across several other Maven modules. In this module I want to create some singleton:
package org.me.util;
public interface Baz {
String myMethod(String s);
}
@Singleton
public class Foo implements Baz {
private Bar bar;
@Inject
Foo(Bar bar) {
this.bar = bar;
}
@Override
public String myMethod(String s) {
return s;
}
}
Then I bind my interface with:
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(Baz.class).to(Foo.class);
}
}
Suppose I want to use this singleton from another Maven module (say, a web service), how do I achieve this? The only way I found was to create a class in my util Maven module like:
package org.me.util;
public class Main {
private static Injector injector = Guice.createInjector(new MyModule());;
public static Injector getInjector() {
return injector;
}
Alternatively I could create the injector in a static main method as seen in the Guice tutorials, and save an instance somewhere.
Then from my web service do something like:
Baz baz = Main.getInjector().getInstance(Baz.class);
But this does not seem very elegant because I have to pass my injector around (in this case by providing it with a static getter).
Is there any other way? Thanks.
@Inject Baz bazand then get an instance of whatever needsBazfrom the injector? - condit@Injectyour singleton where you need it, if possible. Guice can only help you if it's creating the objects. - condit