What you are assuming is not completely right: Guice is used for dependency injection, which means that you can inject some interface/class into the constructor of another class.
Lets say you have an interface Foo
and it's implementation FooImpl
. Then you also have a class Bar
which depends on an implementation of Foo
.
public class Bar {
private Foo foo;
@Inject
public Bar(@Named("foo") Foo foo) {
this.foo = foo;
}
//some other methods
}
In your Guice-module you have to write
bind(Foo.class).annotatedWith(Names.named("Foo")).toInstance(foo);
//let's say this is part of the module MyModule extends AbstractModule
Once you set this up, you can make a main-method where you create an object by using Guice's Injector
-class. Like so:
Injector injector = Guice.createInjector(new MyModule());
Bar bar = injector.getInstance(Bar.class);
//do something with bar
Hope this helped you with it. If you have more questions, feel free to ask me!
Hint: check the website of Guice, watch the video overthere and read the wiki carefully. Guice is a really great tool, but you need to do some study before you use it.
Good luck!
Addition: In my opinion using @Named
is a bad codestyle. You can better define your own annotations. For example:
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface FooAnnotation {
}
Then replace @Named("foo")
by @FooAnnotation
in the Bar
class and replace Names.named("Foo")
by FooAnnotation.class
in your module.