Skip to content

Example: Automatic Binding

manzke edited this page Nov 5, 2010 · 4 revisions

This should be just a small Example, how to use the Automatic Binding. You have to annotate your Implementations, with @Bind. This allow GAB, to find them.

If you use the @Bind, without any modification, GAB will bind your Class to all known Interfaces. If annotated with javax.inject.Named or com.google.inject.Named, it will be a named Binding. If the Annotation is not used, you could use @Named in the @Bind-Annotation. This allows to override it. So use, what you like too. :)

Google Guice also allows Multiple Bindings. If you want, that your class is bound with the Multibinding-Extension, just set the "multiple" Attribute to true.

@Bind also allows a lot of customizations. So think about it like the ESL of Guice. If for example you want, that your Implemenation should not be bound to the Interfaces, you can use the "to" Attribute to specify a Binding to the** Super-Class**, Implementation-only or Custom.

If you choose Custom, you can specify the Classes, it should be bound to. Implementation-only is for example used, by JAX-RS, so it recognizes the Resources.

public interface Example {
	String sayHello();
}
@Bind
public class ExampleImpl implements Example {
	@Override
	public String sayHello() {
		return "yeahhh!!!";
	}
}
public class ExampleApp implements ExampleApplication {
	@Override
	public void run() {
		Injector injector = Guice.createInjector(
				StartupModule.create(ASMClasspathScanner.class, PackageFilter.create(ExampleApp.class)));

		System.out.println(injector.getInstance(Example.class).sayHello());
	}

	public static void main(String[] args) throws IOException {
		new ExampleApp().run();
	}
}