{"id":487,"date":"2008-03-14T00:00:00","date_gmt":"2008-03-13T16:00:00","guid":{"rendered":"http:\/\/www.strongd.net\/?p=487"},"modified":"2011-07-15T09:36:22","modified_gmt":"2011-07-15T01:36:22","slug":"java-on-guice","status":"publish","type":"post","link":"https:\/\/www.strongd.net\/?p=487","title":{"rendered":"Java on Guice"},"content":{"rendered":"<p><STRONG><FONT color=#666666 size=6>Java on Guice<BR><\/FONT><FONT style=\"COLOR: rgb(0,0,0)\" size=3>Guice 1.0 User&#8217;s Guide<\/FONT><\/STRONG><BR><br \/>\n<P style=\"MARGIN-LEFT: 40px\"><BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 40px\"><BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 40px\"><I>Guice<\/I> (pronounced &#8220;juice&#8221;) is an ultra-lightweight, next-generation dependency injection container for Java 5 and later.<BR><\/P><br \/>\n<H1>Introduction<BR><\/H1><br \/>\n<P style=\"MARGIN-LEFT: 40px\">The enterprise Java community exerts a lot of effort toward wiring objects together. How does your web application get access to a middle tier service, or your service to the logged in user or transaction manager? You&#8217;ll find many general and specific solutions to this problem. Some rely on patterns. Others use frameworks. All result in varying degrees of testability and some amount of boilerplate code. You&#8217;ll soon see that Guice enables the best of all worlds: easy unit testing, maximal flexibility and maintainability, and minimal repetition.<\/P><BR><br \/>\n<P style=\"MARGIN-LEFT: 40px; TEXT-ALIGN: left\">We&#8217;ll use an unrealistically simple example to illustrate the benefits of Guice over some classic approaches which you&#8217;re probably already familiar with. The following example is so simple in fact that, even though it will show immediate benefits, we won&#8217;t actually do Guice justice. We hope you&#8217;ll see that as your application grows, Guice&#8217;s benefits accelerate.<BR><\/P><BR><br \/>\n<P style=\"MARGIN-LEFT: 40px\">In this example, a client depends on a service interface. This could be any arbitrary service. We&#8217;ll just call it <SPAN style=\"FONT-FAMILY: Courier New\">Service<\/SPAN>.<BR><\/P><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><\/DIV><br \/>\n<P style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">public interface Service {<BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 80px\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; void go();<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">}<\/SPAN><BR><\/P><BR><br \/>\n<P style=\"MARGIN-LEFT: 40px\">We have a default implementation of this service which the client should not depend directly on. If we decide to use a different service implementation in the future, we don&#8217;t want to go around and change all of our clients.<\/P><br \/>\n<P style=\"MARGIN-LEFT: 40px\"><BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">public class ServiceImpl implements Service {<BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">&nbsp; public void go() {<\/P><br \/>\n<P style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; &#8230;<\/P><br \/>\n<P style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">&nbsp; }<\/P><br \/>\n<P style=\"MARGIN-LEFT: 80px\"><SPAN style=\"FONT-FAMILY: Courier New\">}<\/SPAN> <\/P><br \/>\n<P style=\"MARGIN-LEFT: 40px\"><BR>We also have a mock service which we can use in unit tests.<\/P><BR><br \/>\n<P style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">public class MockService implements Service {<\/P><br \/>\n<P style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\"><BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 80px\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; private boolean gone = false;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public void go() {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; gone = true;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public boolean isGone() {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; return gone;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">}<\/SPAN><BR><\/P><br \/>\n<H2>Plain Old Factories<\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Before we discovered dependency injection, we mostly used the factory pattern. In addition to the service interface, you have a service factory which provides the service to clients as well as a way for tests to pass in a mock service. We&#8217;ll make the service a singleton so we can keep this example as simple as possible.<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">public class ServiceFactory {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; private ServiceFactory() {}<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; <\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; private static Service instance = new ServiceImpl();<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public static Service getInstance() {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; return instance;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; <\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public static void setInstance(Service service) {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; instance = service;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">} <\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<P style=\"MARGIN-LEFT: 40px\">Our client goes directly to the factory every time it needs a service.<BR><\/P><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">public class Client {<BR><BR>&nbsp; public void go() {<BR>&nbsp;&nbsp;&nbsp; Service service = ServiceFactory.getInstance();<BR>&nbsp;&nbsp;&nbsp; service.go();<BR>&nbsp; }<BR>}<BR><\/DIV><br \/>\n<P style=\"MARGIN-LEFT: 40px\"><BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 40px\">The client is simple enough, but the unit test for the client has to pass in a mock service and then remember to clean up afterwards. This isn&#8217;t such a big deal in our simple example, but as you add more clients and services, all this mocking and cleaning up creates friction for unit test writing. Also, if you forget to clean up after your test, other tests may succeed or fail when they shouldn&#8217;t. Even worse, tests may fail depending on which order you run them in.<BR><\/P><BR><br \/>\n<P style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">public void testClient() {<BR>&nbsp; Service previous = ServiceFactory.getInstance();<BR>&nbsp; try {<BR>&nbsp;&nbsp;&nbsp; final MockService mock = new MockService();<BR>&nbsp;&nbsp;&nbsp; ServiceFactory.setInstance(mock);<BR>&nbsp;&nbsp;&nbsp; Client client = new Client();<BR>&nbsp;&nbsp;&nbsp; client.go();<BR>&nbsp;&nbsp;&nbsp; assertTrue(mock.isGone());<BR>&nbsp; }<BR>&nbsp; finally {<BR>&nbsp;&nbsp;&nbsp; ServiceFactory.setInstance(previous);<BR>&nbsp; }<BR>}<BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 40px\"><BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 40px\">Finally, note that the service factory&#8217;s API ties us to a singleton approach. Even if <SPAN style=\"FONT-FAMILY: Courier New\">getInstance()<\/SPAN> could return multiple instances, <SPAN style=\"FONT-FAMILY: Courier New\">setInstance()<\/SPAN> ties our hands. Moving to a non-singleton implementation would mean switching to a more complex API.<BR><\/P><br \/>\n<H2>Dependency Injection By Hand<BR><\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">The dependency injection pattern aims in part to make unit testing easier. We don&#8217;t necessarily need a specialized framework to practice dependency injection. You can get roughly 80% of the benefit writing code by hand.<BR><BR>While the client asked the factory for a service in our previous example, with dependency injection, the client expects to have its dependency passed in. Don&#8217;t call me, I&#8217;ll call you, so to speak.<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">public class Client {<BR>&nbsp;&nbsp;&nbsp; <BR>&nbsp; private final Service service;<BR><BR>&nbsp; public Client(Service service) {<BR>&nbsp;&nbsp;&nbsp; this.service = service;<BR>&nbsp; }<BR><BR>&nbsp; public void go() {<BR>&nbsp;&nbsp;&nbsp; service.go();<BR>&nbsp; }<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">This simplifies our unit test considerably. We can just pass in a mock service and throw everything away when we&#8217;re done.<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">public void testClient() {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; MockService mock = new MockService();<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; Client client = new Client(mock);<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; client.go();<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; assertTrue(mock.isGone());<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">}<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">We can also tell from the API exactly what the client depends on.<BR><BR>Now, how do we connect the client with a service? When implementing dependency injection by hand, we can move all dependency logic into factory classes. This means we need a factory for our client, too.<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">public static class ClientFactory {<BR><BR>&nbsp; private ClientFactory() {}<BR><BR>&nbsp; public static Client getInstance() {<BR>&nbsp;&nbsp;&nbsp; Service service = ServiceFactory.getInstance();<BR>&nbsp;&nbsp;&nbsp; return new Client(service);<BR>&nbsp; }<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Implementing dependency injection by hand requires roughly the same number of lines of code as plain old factories.<BR><\/DIV><br \/>\n<H2>Dependency Injection with Guice<\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Writing factories and dependency injection logic by hand for every service and client can become tedious. Some other dependency injection frameworks even require you to explicitly map services to the places where you want them injected.<BR><BR>Guice aims to eliminate all of this boilerplate without sacrificing maintainability.<BR><BR>With Guice, you implement modules. Guice passes a binder to your module, and your module uses the binder to map interfaces to implementations. The following module tells Guice to map <SPAN style=\"FONT-FAMILY: Courier New\">Service<\/SPAN> to <SPAN style=\"FONT-FAMILY: Courier New\">ServiceImpl<\/SPAN> in singleton scope:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">public class MyModule implements Module {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public void configure(Binder binder) {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; binder.bind(Service.class)<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .to(ServiceImpl.class)<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .in(Scopes.SINGLETON);<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">}<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">A module tells Guice what we want to inject. Now, how do we tell Guice where we want it injected? With Guice, you annotate constructors, methods and fields with <SPAN style=\"FONT-FAMILY: Courier New\">@Inject<\/SPAN>.<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">public class Client {<BR><BR>&nbsp; private final Service service;<BR><BR>&nbsp; <B>@Inject<\/B><BR>&nbsp; public Client(Service service) {<BR>&nbsp;&nbsp;&nbsp; this.service = service;<BR>&nbsp; }<BR><BR>&nbsp; public void go() {<BR>&nbsp;&nbsp;&nbsp; service.go();<BR>&nbsp; }<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">The <SPAN style=\"FONT-FAMILY: Courier New\">@Inject<\/SPAN> annotation makes it clear to a programmer editing your class which members are injected.<BR><BR>For Guice to inject <SPAN style=\"FONT-FAMILY: Courier New\">Client<\/SPAN>, we must either directly ask Guice to create a <SPAN style=\"FONT-FAMILY: Courier New\">Client<\/SPAN> instance for us, or some other class must have <SPAN style=\"FONT-FAMILY: Courier New\">Client<\/SPAN> injected into it.<BR><\/DIV><br \/>\n<H3>Guice vs. Dependency Injection By Hand<\/H3><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">As you can see, Guice saves you from having to write factory classes. You don&#8217;t have to write explicit code wiring clients to their dependencies. If you forget to provide a dependency, Guice fails at startup. Guice handles circular dependencies automatically. <BR><BR>Guice enables you to specify scopes declaratively. For example, you don&#8217;t have to write the same code to store an object in the <SPAN style=\"FONT-FAMILY: Courier New\">HttpSession<\/SPAN> over and over.<BR><BR>In the real world, you often don&#8217;t know an implementation class until runtime. You need meta factories or service locators for your factories. Guice addresses these problems with minimal effort.<BR><BR>When injecting dependencies by hand, you can easily slip back into old habits and introduce direct dependencies, especially if you&#8217;re new to the concept of dependency injection. Using Guice turns the tables and makes doing the right thing easier. Guice helps keep you on track.<BR><\/DIV><br \/>\n<H2>More Annotations<\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">When possible, Guice enables you to use annotations in lieu of explicit bindings and eliminate even more boilerplate code. Back to our example, if you need an interface to simplify unit testing but you don&#8217;t care about compile time dependencies, you can point to a default implementation directly from your interface.<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\"><B>@ImplementedBy(ServiceImpl.class)<\/B><BR style=\"FONT-WEIGHT: bold\">public interface Service {<BR>&nbsp; void go();<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">If a client needs a <SPAN style=\"FONT-FAMILY: Courier New\">Service<\/SPAN> and Guice can&#8217;t find an explicit binding, Guice will inject an instance of <SPAN style=\"FONT-FAMILY: Courier New\">ServiceImpl<\/SPAN>.<BR><BR>By default, Guice injects a new instance every time. If you want to specify a different scope, you can annotate the implementation class, too.<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\"><B>@Singleton<\/B><BR style=\"FONT-WEIGHT: bold\">public class ServiceImpl implements Service {<BR>&nbsp; public void go() {<BR>&nbsp;&nbsp;&nbsp; &#8230;<BR>&nbsp; }<BR>}<BR><\/DIV><\/DIV><br \/>\n<H1>Architectural Overview<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">We can break Guice&#8217;s architecture down into two distinct stages: startup and runtime. You build an <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN> during startup and use it to inject objects at runtime.<BR><\/DIV><br \/>\n<H2>Startup<\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">You configure Guice by implementing <SPAN style=\"FONT-FAMILY: Courier New\">Module<\/SPAN>. You pass Guice a module, Guice passes your module a <SPAN style=\"FONT-FAMILY: Courier New\">Binder<\/SPAN>, and your module uses the binder to configure bindings. A binding most commonly consists of a mapping between an interface and a concrete implementation. For example:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">public class MyModule implements Module {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public void configure(Binder binder) {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; \/\/ Bind Foo to FooImpl. Guice will create a new<BR>&nbsp;&nbsp;&nbsp; \/\/ instance of FooImpl for every injection.<BR>&nbsp;&nbsp;&nbsp; binder.bind(Foo.class)<\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\">.to(FooImpl.class);<BR><BR>&nbsp;&nbsp;&nbsp; \/\/ Bind Bar to an instance of Bar.<BR>&nbsp;&nbsp;&nbsp; Bar bar = new Bar();<BR>&nbsp;&nbsp;&nbsp; binder.bind(Bar.class).toInstance(bar);<BR style=\"FONT-FAMILY: Courier New\"><\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">}<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Guice can look at the classes you tell it about during this stage and any classes those classes know about, and tell you whether or not you&#8217;re missing any dependencies. For example, in a Struts 2 application, Guice knows about all of your actions. Guice can validate your actions and anything they transitively depend on, and fail early if necessary.<BR><BR>Creating an <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN> entails the following steps:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><\/DIV><br \/>\n<P style=\"MARGIN-LEFT: 40px\"><IMG style=\"WIDTH: 715px; HEIGHT: 283px\" src=\"http:\/\/docs.google.com\/File?id=dd2fhx4z_29f8h7x7\"><\/P><BR><br \/>\n<OL style=\"MARGIN-LEFT: 40px\"><br \/>\n<LI>First, create an instance of your module and pass it to <SPAN style=\"FONT-FAMILY: Courier New\">Guice.createInjector()<\/SPAN>.<br \/>\n<LI>Guice creates a <SPAN style=\"FONT-FAMILY: Courier New\">Binder<\/SPAN> and passes it to your module.<br \/>\n<LI>Your module uses the binder to define bindings.<br \/>\n<LI>Based on the bindings you specified, Guice creates an <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN> and returns it to you.<br \/>\n<LI>You use the injector to inject an object.<\/LI><\/OL><br \/>\n<H2>Runtime<\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">We can now use the injector we created during the first stage to inject objects and introspect on our bindings. Guice&#8217;s runtime model consists of an injector which contains some number of bindings.<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><IMG style=\"WIDTH: 578px; HEIGHT: 216px\" src=\"http:\/\/docs.google.com\/File?id=dd2fhx4z_30f3dppc\"><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">A <SPAN style=\"FONT-FAMILY: Courier New\">Key<\/SPAN> uniquely identifies each binding. The key consists of a type which the client depends on and an optional annotation. You can use an annotation to differentiate multiple bindings to the same type. The key&#8217;s type and annotation correspond to the type and annotation at a point of injection.<BR><BR>Each binding has a provider which provides instances of the necessary type. You can provide a class, and Guice will create instances of it for you. You can give Guice an instance of the type you&#8217;re binding to. You can implement your own provider, and Guice can inject dependencies into it.<BR><BR>Each binding also has an optional scope. Bindings have no scope by default, and Guice creates a new instance for every injection. A custom scope enables you to control whether or not Guice creates a new instance. For example, you can create one instance per <SPAN style=\"FONT-FAMILY: Courier New\">HttpSession<\/SPAN>.<\/DIV><br \/>\n<H2>Bootstrapping Your Application<BR><\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">The idea of <I>bootstrapping<\/I> is fundamental to dependency injection. Always explicitly asking the <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN> for dependencies would be using Guice as a service locator, not a dependency injection framework.<BR><BR>Your code should deal directly with the <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN> as little as possible. Instead, you want to bootstrap your application by injecting one root object. The container can further inject dependencies into the root object&#8217;s dependencies, and so on recursively. In the end, your application should ideally have one class (if that many) which knows about the <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN>, and every other class should expect to have dependencies injected.<BR><BR>For example, a web application framework such as Struts 2 bootstraps your application by injecting all of your actions. You might bootstrap a web service framework by injecting your service implementation classes.<BR><BR>Dependency injection is viral. If you&#8217;re refactoring an existing code base with a lot of static methods, you may start to feel like you&#8217;re pulling a never-ending thread. This is a Good Thing. It means dependency injection is making your code more flexible and testable.<BR><BR>If you get in over your head, rather than try to refactor an entire code base all in one shot, you might <I>temporarily<\/I> store a reference to the <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN> in a static field somewhere or use static injection. Name the field&#8217;s class clearly though: <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\">Hack<\/SPAN> and <SPAN style=\"FONT-FAMILY: Courier New\">GodKillsAKittenEveryTimeYouUseMe<\/SPAN> come to mind. Keep in mind that you you&#8217;ll have to mock this class, and your unit tests will have to install an Injector here by hand, and remember to clean up afterwards.<BR><\/DIV><br \/>\n<H1>Binding Dependencies <\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">How does Guice know what to inject? For starters, a <A title=Key style=\"FONT-FAMILY: Courier New\" href=\"http:\/\/google-guice.googlecode.com\/svn\/trunk\/javadoc\/com\/google\/inject\/Key.html\">Key<\/A> composed of a type and an optional annotation uniquely identifies a dependency. Guice refers to the mapping between a key and an implementation as a <A title=Binding style=\"FONT-FAMILY: Courier New\" href=\"http:\/\/google-guice.googlecode.com\/svn\/trunk\/javadoc\/com\/google\/inject\/Binding.html\">Binding<\/A>. An implementation can consist of a single object, a class which Guice should also inject, or a custom provider.<BR><BR><br \/>\n<P>When injecting a dependency, Guice first looks for an <I>explicit<\/I> binding, a binding which you specified using the <A title=ContainerBuilder style=\"FONT-FAMILY: Courier New\" href=\"http:\/\/google-guice.googlecode.com\/svn\/trunk\/javadoc\/com\/google\/inject\/Binder.html\">Binder<\/A>. The <SPAN style=\"FONT-FAMILY: Courier New\">Binder<\/SPAN> API uses the builder pattern to create a domain-specific expression language. Different methods return different objects depending on the context limiting you to appropriate methods.<\/P><br \/>\n<P><BR><\/P><br \/>\n<P>For example, to bind an interface <SPAN style=\"FONT-FAMILY: Courier New\">Service<\/SPAN> to a concrete implementation <SPAN style=\"FONT-FAMILY: Courier New\">ServiceImpl<\/SPAN>, call: <\/P><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">binder.bind(Service.class).to(ServiceImpl.class);<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">This binding matches the following the method:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">@Inject<BR>void injectService(Service service) {<BR>&nbsp; &#8230;<BR>}<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\"><\/DIV><\/DIV><br \/>\n<BLOCKQUOTE style=\"MARGIN-LEFT: 40px\"><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><B>Note: <\/B>In contrast to some other frameworks, Guice gives no special treatment to &#8220;setter&#8221; methods. Guice will inject any method with any number of parameters so long as the method has an <SPAN style=\"FONT-FAMILY: Courier New\">@Inject<\/SPAN> annotation, even if the method is in a superclass.<BR><\/DIV><\/BLOCKQUOTE><br \/>\n<H3><B>DRY (Don&#8217;t Repeat Yourself)<\/B><BR><\/H3><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Repeating &#8220;<SPAN style=\"FONT-FAMILY: Courier New\">binder<\/SPAN>&#8221; over and over for each binding can get a little tedious. Guice provides a <SPAN style=\"FONT-FAMILY: Courier New\">Module<\/SPAN> support class named <A title=AbstractModule style=\"FONT-FAMILY: Courier New\" href=\"http:\/\/google-guice.googlecode.com\/svn\/trunk\/javadoc\/com\/google\/inject\/AbstractModule.html\">AbstractModule<\/A> which implicitly gives you access to <SPAN style=\"FONT-FAMILY: Courier New\">Binder<\/SPAN>&#8216;s methods. For example, we could extend <SPAN style=\"FONT-FAMILY: Courier New\">AbstractModule<\/SPAN> and rewrite the above binding as:<BR><\/DIV><SPAN style=\"FONT-FAMILY: Courier New\"><BR><\/SPAN><br \/>\n<DIV style=\"MARGIN-LEFT: 80px\"><SPAN style=\"FONT-FAMILY: Courier New\">bind(Service.class)<\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\">.to(ServiceImpl.class);<\/SPAN><BR><\/DIV><BR><br \/>\n<P style=\"MARGIN-LEFT: 40px\">We&#8217;ll use this syntax throughout the rest of the guide.<BR><\/P><br \/>\n<H2>Annotating Bindings<BR><\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">If you need multiple bindings to the same type, you can differentiate the bindings with annotations.&nbsp; For example, to bind an interface <SPAN style=\"FONT-FAMILY: Courier New\">Service<\/SPAN> and annotation <SPAN style=\"FONT-FAMILY: Courier New\">@Blue<\/SPAN> to the concrete implementation <SPAN style=\"FONT-FAMILY: Courier New\">BlueService<\/SPAN>, call:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">bind(Service.class)<\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\"><BR><B>&nbsp; .annotatedWith(Blue.class)<\/B><\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\"><BR>&nbsp; .to(BlueService.class);<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">This binding matches the following the method:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">@Inject<BR>void injectService(<B>@Blue<\/B> Service service) {<BR>&nbsp; &#8230;<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Notice that while <SPAN style=\"FONT-FAMILY: Courier New\">@Inject<\/SPAN> goes on the method, binding annotations such as <SPAN style=\"FONT-FAMILY: Courier New\">@Blue<\/SPAN> go directly on the parameter. The same goes for constructors. When using field injection, both annotations can apply directly to the field, as in this example:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\"><B>@Inject @Blue<\/B> Service service;<BR><\/DIV><\/DIV><br \/>\n<H3><B>Creating Binding Annotations<\/B><\/H3><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><br \/>\n<H3><\/H3>Where did this <SPAN style=\"FONT-FAMILY: Courier New\">@Blue<\/SPAN> annotation just mentioned come from?&nbsp; You can create such an annotation easily, although the standard incantation you have to use is unfortunately a little complex:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">\/**<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;* Indicates we want the blue version of a binding.<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;*\/<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">@Retention(RetentionPolicy.RUNTIME)<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">@Target({ElementType.FIELD, ElementType.PARAMETER})<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">@BindingAnnotation<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">public @interface Blue {}<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><\/DIV><BR>Luckily, we don&#8217;t really have to understand it all just to use it.&nbsp; But for the curious, here&#8217;s what all this boilerplate means:<BR><BR><br \/>\n<UL><br \/>\n<LI><SPAN style=\"FONT-FAMILY: Courier New\">@Retention(RUNTIME)<\/SPAN> allows your annotation to be visible at runtime.<br \/>\n<LI><SPAN style=\"FONT-FAMILY: Courier New\">@Target({FIELD, PARAMETER})<\/SPAN> is a courtesy to your users; it prevents <SPAN style=\"FONT-FAMILY: Courier New\">@Blue<\/SPAN> from being applied to methods, types, local variables, and other annotations, where it would serve no purpose.<br \/>\n<LI><SPAN style=\"FONT-FAMILY: Courier New\">@BindingAnnotation<\/SPAN> is a Guice-specific signal that you wish your annotation to be used in this way.&nbsp; Guice will produce an error whenever user applies more than one binding annotation to the same injectable element. <\/LI><\/UL><\/DIV><br \/>\n<H3>Annotations With Attributes<\/H3><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">If you can get by with marker annotations alone, feel free to skip to the next section.<BR><BR>You can also bind to annotation instances, i.e. you can have multiple bindings with the same type and annotation type, but with different annotation attribute values. If Guice can&#8217;t find a binding to an annotation instance with the necessary attribute values, it will look for a binding to the annotation type instead.<BR><BR>Say for example we have a binding annotation <SPAN style=\"FONT-FAMILY: Courier New\">@Named<\/SPAN> with a single string attribute value.<BR><\/DIV><PRE style=\"MARGIN-LEFT: 80px; FONT-FAMILY: Courier New\">@Retention(RUNTIME)<BR>@Target({ FIELD, PARAMETER })<BR>@BindingAnnotation<BR>public @interface Named {<BR>  String value();<BR>}<BR><\/PRE><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">If we want to bind to <SPAN style=\"FONT-FAMILY: Courier New\">@Named(&#8220;Bob&#8221;)<\/SPAN>, we first need an implementation of <SPAN style=\"FONT-FAMILY: Courier New\">Named<\/SPAN>. Our implementation must abide by the <SPAN style=\"FONT-FAMILY: Courier New\">Annotation<\/SPAN> contract, specifically the implementations of <SPAN style=\"FONT-FAMILY: Courier New\">hashCode()<\/SPAN> and <SPAN style=\"FONT-FAMILY: Courier New\">equals()<\/SPAN>.<BR><PRE style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">class NamedAnnotation implements Named {<BR><BR>  final String value;<BR><BR>  public NamedAnnotation(String value) {<BR>    this.value = value;<BR>  }<BR><BR>  public String value() {<BR>    return this.value;<BR>  }<BR><BR>  public int hashCode() {<BR>    \/\/ This is specified in java.lang.Annotation.<BR>    return 127 * &#8220;value&#8221;.hashCode() ^ value.hashCode();<BR>  }<BR><BR>  public boolean equals(Object o) {<BR>    if (!(o instanceof Named))<BR>      return false;<BR>    Named other = (Named) o;<BR>    return value.equals(other.value());<BR>  }<BR><BR>  public String toString() {<BR>    return &#8220;@&#8221; + Named.class.getName() + &#8220;(value=&#8221; + value + &#8220;)&#8221;;<BR>  }<BR><BR>  public Class&lt;? extends Annotation&gt; annotationType() {<BR>    return Named.class;<BR>  }<BR>}<\/PRE>Now we can use this annotation implementation to create bindings to <SPAN style=\"FONT-FAMILY: Courier New\">@Named<\/SPAN>.<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">bind(Person.class)<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; .annotatedWith(new NamedAnnotation(&#8220;Bob&#8221;))<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; .to(Bob.class);<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">This may seem like a lot of work compared to string based identifiers used by other frameworks, but keep in mind that you can&#8217;t do this at all with string-based identifiers. Also, you&#8217;ll find that you get a lot of reuse out of binding annotations.<BR><BR>Since identifying a binding by name is such a common use case, Guice provides a production-worthy implementation of <SPAN style=\"FONT-FAMILY: Courier New\">@Named<\/SPAN> in <SPAN style=\"FONT-FAMILY: Courier New\">com.google.inject.name<\/SPAN>.<BR><\/DIV><br \/>\n<H1><\/H1><br \/>\n<H1>Implicit Bindings <\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">As we saw in the introduction, you don&#8217;t always have to declare bindings explicitly. In the absence of an explicit binding, Guice will try to inject and create a new instance of the class you depend on. If you depend on an interface, Guice will look for an <SPAN style=\"FONT-FAMILY: Courier New\">@ImplementedBy<\/SPAN> annotation which points to the concrete implementation. Take the following explicit binding to a concrete, injectable class named <SPAN style=\"FONT-FAMILY: Courier New\">Concrete<\/SPAN> for example. It basically says, bind <SPAN style=\"FONT-FAMILY: Courier New\">Concrete<\/SPAN> to <SPAN style=\"FONT-FAMILY: Courier New\">Concrete<\/SPAN>. That&#8217;s explicit, but also a little redundant.<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">bind(Concrete.class);<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Removing the binding above would not affect the behavior of this class:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">class Mixer {<BR><BR>&nbsp; @Inject<BR>&nbsp; Mixer(Concrete concrete) {<BR>&nbsp;&nbsp;&nbsp; &#8230;<BR>&nbsp; }<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">So, take your pick: explicit or brief. In the event of an error, Guice will produce helpful messages either way.<BR><\/DIV><br \/>\n<H1>Injecting Providers <\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Sometimes a client needs multiple instances of a dependency per injection. Other times a client may not want to actually retrieve an object until some time after the actual injection (if at all). For any binding of type <SPAN style=\"FONT-FAMILY: Courier New\">T<\/SPAN>, rather than inject an instance of <SPAN style=\"FONT-FAMILY: Courier New\">T<\/SPAN> directly, you can inject a <SPAN style=\"FONT-FAMILY: Courier New\">Provider&lt;T&gt;<\/SPAN>. Then call <SPAN style=\"FONT-FAMILY: Courier New\">Provider&lt;T&gt;<\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\">.get()<\/SPAN> as necessary. For example:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">@Inject<BR>void injectAtm(Provider&lt;Money&gt; atm) {<BR>&nbsp; Money one = atm.get();<BR>&nbsp; Money two = atm.get();<BR>&nbsp; &#8230;<BR>}<BR><\/DIV><\/DIV><BR><br \/>\n<P style=\"MARGIN-LEFT: 40px\">As you can see, the <SPAN style=\"FONT-FAMILY: Courier New\">Provider<\/SPAN> interface couldn&#8217;t get much simpler so it doesn&#8217;t get in the way of easy unit testing.<BR><\/P><br \/>\n<H1>Injecting Constant Values<BR><\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">When it comes to constant values, Guice gives special treatment to several types:<BR><BR><br \/>\n<UL><br \/>\n<LI>Primitive types (int, char, &#8230;)<br \/>\n<LI>Primitive wrapper types (Integer, Character, &#8230;)<br \/>\n<LI>Strings<br \/>\n<LI>Enums<br \/>\n<LI>Classes <\/LI><\/UL><BR>First, when binding to constant values of these types, you needn&#8217;t specify the type you&#8217;re binding to. Guice can figure it out from the value. For example, given a binding annotation named <SPAN style=\"FONT-FAMILY: Courier New\">TheAnswer<\/SPAN>:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">bindConstant().annotatedWith(TheAnswer.class)<\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\">.to(42);<BR><\/SPAN><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Has the same effect as:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">bind(int.class).annotatedWith(TheAnswer.class).toInstance(42);<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">When it comes time to inject a value of one of these types, if Guice can&#8217;t find an explicit binding for a primitive type, it will look for a binding to the corresponding wrapper type and vice versa.<BR><\/DIV><br \/>\n<H3><B>Converting Strings<\/B><\/H3><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><br \/>\n<H3><\/H3>If Guice still can&#8217;t find an explicit binding for one of the above types, it will look for a constant <SPAN style=\"FONT-FAMILY: Courier New\">String<\/SPAN> binding with the same binding annotation and try to convert its value. For example:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">bindConstant().annotatedWith(TheAnswer.class)<\/SPAN><SPAN style=\"FONT-FAMILY: Courier New\">.to(&#8220;42&#8221;); \/\/ String!<BR><\/SPAN><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Will match:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">@Inject @TheAnswer int answer;<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">When converting, Guice will try to look up enums and classes by name. Guice converts a value once at startup which also means you get up front type checking. This feature comes in especially handy if the binding value comes from a properties file for example.<BR><\/DIV><br \/>\n<H1>Custom Providers<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Sometimes you need to create your objects manually rather than let Guice create them. For example, you might not be able to add <SPAN style=\"FONT-FAMILY: Courier New\">@Inject<\/SPAN> annotations to the implementation class as it came from a 3rd party. In these cases, you can implement a custom <SPAN style=\"FONT-FAMILY: Courier New\">Provider<\/SPAN>. Guice can even inject your provider class. For example:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">class WidgetProvider implements Provider&lt;Widget&gt; {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; final Service service;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; @Inject<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; WidgetProvider(Service service) {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; this.service = service;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public Widget get() {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; return new Widget(service);<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">}<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">You bind <SPAN style=\"FONT-FAMILY: Courier New\">Widget<\/SPAN> to <SPAN style=\"FONT-FAMILY: Courier New\">WidgetProvider<\/SPAN> like so:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">bind(Widget.class).toProvider(WidgetProvider.class);<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Injecting the custom providers enables Guice to check the types and dependencies up front. Custom providers can reside in any scope independent of the scope of the objects they provide. By default, Guice creates a new provider instance for every injection. In the above example, if each <SPAN style=\"FONT-FAMILY: Courier New\">Widget<\/SPAN> needs its own instance of <SPAN style=\"FONT-FAMILY: Courier New\">Service<\/SPAN>, our code will work fine. You can specify a different scope for a custom factory using a scope annotation on the factory class or by creating a separate binding for the factory.<BR><\/DIV><br \/>\n<H3>Example: Integrating With JNDI<\/H3><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Say for example we want to bind to objects from JNDI. We could implement a reusable custom provider similar to the one below. Notice we inject the JNDI <SPAN style=\"FONT-FAMILY: Courier New\">Context<\/SPAN>:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">package mypackage;<BR><BR>import com.google.inject.*;<BR>import javax.naming.*;<BR><BR>class JndiProvider&lt;T&gt; implements Provider&lt;T&gt; {<BR><BR>&nbsp; @Inject Context context;<BR>&nbsp; final String name;<BR>&nbsp; final Class&lt;T&gt; type;<BR><BR>&nbsp; JndiProvider(Class&lt;T&gt; type, String name) {<BR>&nbsp;&nbsp;&nbsp; this.name = name;<BR>&nbsp;&nbsp;&nbsp; this.type = type;<BR>&nbsp; }<BR><BR>&nbsp; public T get() {<BR>&nbsp;&nbsp;&nbsp; try {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return type.cast(context.lookup(name));<BR>&nbsp;&nbsp;&nbsp; }<BR>&nbsp;&nbsp;&nbsp; catch (NamingException e) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new RuntimeException(e);<BR>&nbsp;&nbsp;&nbsp; }<BR>&nbsp; }<BR><BR>&nbsp; \/**<BR>&nbsp;&nbsp; * Creates a JNDI provider for the given<BR>&nbsp;&nbsp; * type and name.<BR>&nbsp;&nbsp; *\/<BR>&nbsp; static &lt;T&gt; Provider&lt;T&gt; fromJndi(<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Class&lt;T&gt; type, String name) {<BR>&nbsp;&nbsp;&nbsp; return new JndiProvider&lt;T&gt;(type, name);<BR>&nbsp; }<BR>}<BR><\/SPAN><BR><\/DIV><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Thanks to generic type erasure, we must pass in the class at runtime. You could skip this step, but tracking down type casting errors later might be a little tricky (i.e. if JNDI returns an object of the wrong type).<BR><BR>We can use our custom <SPAN style=\"FONT-FAMILY: Courier New\">JndiProvider<\/SPAN> to bind <SPAN style=\"FONT-FAMILY: Courier New\">DataSource<\/SPAN> to an object from JNDI:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR style=\"FONT-FAMILY: Courier New\"><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">import com.google.inject.*;<BR>import static mypackage.JndiProvider.fromJndi;<BR>import javax.naming.*;<BR>import javax.sql.DataSource;<BR><BR>&#8230;<BR><BR>\/\/ Bind Context to the default InitialContext.<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">bind(Context.class).to(InitialContext.class);<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">\/\/ Bind to DataSource from JNDI.<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">bind(DataSource.class)<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; .toProvider(fromJndi(DataSource.class, &#8220;&#8230;&#8221;));<BR><\/SPAN><\/DIV><\/DIV><br \/>\n<H1>Scoping Bindings<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">By default, Guice creates a new object for every injection. We refer to this as having &#8220;no scope.&#8221; You can specify a scope when you configure a binding. For example, to inject the same instance every time:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">bind(MySingleton.class).in(Scopes.SINGLETON);<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">As an alternative, you can use an annotation on your implementation class to specify the scope. Guice supports <SPAN style=\"FONT-FAMILY: Courier New\">@Singleton<\/SPAN> by default:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">@Singleton<BR>class MySingleton {<BR>&nbsp; &#8230;<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">The annotation approach works with implicit bindings as well but requires that Guice create your objects. On the other hand, calling <SPAN style=\"FONT-FAMILY: Courier New\">in()<\/SPAN> works with almost any binding type (binding to a single instance being an obvious exception) and overrides annotations when present. <SPAN style=\"FONT-FAMILY: Courier New\">in()<\/SPAN> also accepts annotations if you don&#8217;t want a compile time dependency on your scope implementation.<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><br \/>\n<P>Specify annotations for custom scopes using <SPAN style=\"FONT-FAMILY: Courier New\">Binder.bindScope()<\/SPAN>. For example, given an annotation <SPAN style=\"FONT-FAMILY: Courier New\">@SessionScoped<\/SPAN> and a <SPAN style=\"FONT-FAMILY: Courier New\">Scope<\/SPAN> implementation <SPAN style=\"FONT-FAMILY: Courier New\">ServletScopes.SESSION<\/SPAN>:<\/P><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">binder.bindScope(SessionScoped.class, ServletScopes.SESSION);<BR><\/SPAN><\/DIV><\/DIV><br \/>\n<H3><B>Creating Scope Annotations<\/B><\/H3><br \/>\n<H3 style=\"MARGIN-LEFT: 40px\"><\/H3><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Annotations used for scoping should:<BR><BR><\/DIV><br \/>\n<UL style=\"MARGIN-LEFT: 80px\"><br \/>\n<LI>Have a <SPAN style=\"FONT-FAMILY: Courier New\">@Retention(RUNTIME)<\/SPAN> annotation so we can see the annotation at runtime.<BR><br \/>\n<LI>Have a <SPAN style=\"FONT-FAMILY: Courier New\">@Target({TYPE})<\/SPAN> annotation. Scope annotations only apply to implementation classes..<BR><br \/>\n<LI>Have a <SPAN style=\"FONT-FAMILY: Courier New\">@ScopeAnnotation<\/SPAN> meta-annotation. Only one such annotation can apply to a given class. <\/LI><\/UL><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR>For example:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">\/**<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;* Scopes bindings to the current transaction.<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;*\/<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">@Retention(RUNTIME)<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">@Target({TYPE})<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">@ScopeAnnotation<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">public @interface TransactionScoped {}<\/SPAN><\/DIV><\/DIV><br \/>\n<H2>Eagerly Loading Bindings<BR><\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Guice can wait to load singleton objects until you actually need them. This helps speed up development because your application starts faster and you only initialize what you need. However, sometimes you always want to load an object at startup. You can tell Guice to always eagerly load a singleton like so:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">bind(StartupTask.class).asEagerSingleton();<\/SPAN><BR><\/DIV><\/DIV><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">We frequently use this to implement initialization logic for our application. You can control the ordering of your initialization by creating dependencies on singletons which Guice must instantiate first.<BR><\/DIV><br \/>\n<H2>Injecting Between Scopes<\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">You can safely inject objects from a larger scope into an object from a smaller scope, or the same scope. For example, you can inject an Http session-scoped object into an HTTP request-scoped object. However, injecting into objects with larger scopes is a different story. For example, if you injected a request-scoped object into a singleton, at best, you would get an error due to not running within an HTTP request, and at worst your singleton object would always reference an object from the first request. In these cases, you should inject a <SPAN style=\"FONT-FAMILY: Courier New\">Provider&lt;T&gt;<\/SPAN> instead and use it to retrieve the object from the smaller scope as necessary.&nbsp; Then, you should be certain to never invoke this provider when you are outside of <SPAN style=\"FONT-FAMILY: Courier New\">T<\/SPAN>&#8216;s scope (for example, when you are not servicing an HTTP request, and <SPAN style=\"FONT-FAMILY: Courier New\">T<\/SPAN> is request-scoped).<BR><\/DIV><br \/>\n<H1>Development Stages<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Guice is aware that your application goes through different stages of development. You can tell it which stage the application is running in when you create a container. Guice currently supports &#8220;development&#8221; and &#8220;production.&#8221; We&#8217;ve found that tests usually fall under one stage or the other. <BR><BR>During development, Guice will load singleton objects on demand. This way, your application starts up fast and only loads the parts you&#8217;re testing. <BR><BR>In production, Guice will load all your singleton objects at startup. This helps catch errors early and takes any performance hits up front.<BR><BR>Your modules can also apply method interceptors and other bindings based on the current stage. For example, an interceptor might verify that you don&#8217;t use your objects out of scope during development.<BR><\/DIV><br \/>\n<H1>Intercepting Methods<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Guice supports simple method interception using the <A title=\"AOP Alliance API\" href=\"http:\/\/aopalliance.sourceforge.net\/\">AOP Alliance API<\/A>. You can bind interceptors from your modules using <SPAN style=\"FONT-FAMILY: Courier New\">Binder<\/SPAN>. For example, to apply a transaction interceptor to methods annotated with <SPAN style=\"FONT-FAMILY: Courier New\">@Transactional<\/SPAN>:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">import static com.google.inject.matcher.Matchers.*;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&#8230;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">binder.bindInterceptor(<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; any(),&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ Match classes.<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; annotatedWith(Transactional.class), \/\/ Match methods. <\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; new TransactionInterceptor()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ The interceptor.<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">);<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><\/DIV><\/DIV><br \/>\n<P><BR><\/P><br \/>\n<P style=\"MARGIN-LEFT: 40px\">Try to shoulder as much of the filtering as is possible on the matchers rather than in the interceptor&#8217;s body as the matching code runs only once at startup.<BR><\/P><br \/>\n<H1>Static Injection<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Static fields and methods make testing and reusing more difficult, but there are times where your only choice is to keep a static reference to the <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN>.<BR><BR>For these situations, Guice supports injecting less accessible static members. For example, HTTP session objects often need to be serializable to support replication, but what if your session object depends on a container-scoped object? We can keep a transient reference to the object, but how do we look it up again upon deserialization? <BR><BR>We&#8217;ve found the most pragmatic solution to be static injection:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">@SessionScoped<BR>class User {<BR><BR>&nbsp; @Inject<BR>&nbsp; static AuthorizationService authorizationService;<BR>&nbsp; &#8230;<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Guice never performs static injection automatically.&nbsp; You must use <SPAN style=\"FONT-FAMILY: Courier New\">Binder<\/SPAN> to explicitly request that the <SPAN style=\"FONT-FAMILY: Courier New\">Injector<\/SPAN> inject your static members after startup:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">binder.requestStaticInjection(User.class);<\/SPAN><BR><\/DIV><\/DIV><SPAN style=\"FONT-FAMILY: Courier New\"><BR><\/SPAN><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Verdana\">Static injection is a necessary evil, which makes testing more difficult.&nbsp; If you can find a way to avoid using it, you&#8217;ll probably be glad you did.<\/SPAN><BR><\/DIV><br \/>\n<H1>Optional Injection<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Sometimes your code should work whether a binding exists or not. In these cases, you can use <SPAN style=\"FONT-FAMILY: Courier New\">@Inject(optional=true)<\/SPAN> and Guice can override your default implementation with a bound implementation when available. For example:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">@Inject(optional=true) Formatter formatter = new DefaultFormatter();<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><\/DIV><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR>If someone creates a binding for <SPAN style=\"FONT-FAMILY: Courier New\">Formatter<\/SPAN>, Guice will inject an instance from that binding. Otherwise, assuming <SPAN style=\"FONT-FAMILY: Courier New\">Formatter<\/SPAN> isn&#8217;t injectable itself (see <I>Implicit Bindings<\/I>), Guice will skip the optional member.<BR><BR>Optional injection applies only to fields and methods, not constructors. In the case of methods, if a binding for one parameter is missing, Guice won&#8217;t inject the method at all, even if bindings to other parameters are available.<BR><\/DIV><br \/>\n<H1>Binding to Strings<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">We try to avoid using strings whenever possible as they&#8217;re prone to misspellings, not tool friendly, and so on, but using strings instead of creating custom annotations can prove useful for quick and dirty code. For these situations, Guice provides <A title=@Named style=\"FONT-FAMILY: Courier New\" href=\"http:\/\/google-guice.googlecode.com\/svn\/trunk\/javadoc\/com\/google\/inject\/name\/Named.html\">@Named<\/A> and <A title=Names style=\"FONT-FAMILY: Courier New\" href=\"http:\/\/google-guice.googlecode.com\/svn\/trunk\/javadoc\/com\/google\/inject\/name\/Names.html\">Names<\/A>. For example, a binding to a string name like:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">import static com.google.inject.name.Names.*;<BR><BR>&#8230;<BR><BR>bind(named(&#8220;bob&#8221;)).to(10);<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Will match injection points like:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">@Inject @Named(&#8220;bob&#8221;) int score;<\/SPAN><BR><\/DIV><\/DIV><br \/>\n<H1>Struts 2 Support<\/H1><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">To install the Guice Struts 2 plugin with Struts 2.0.6 or later, simply include <SPAN style=\"FONT-FAMILY: Courier New\">guice-struts2-plugin-1.0.jar<\/SPAN> in your web application&#8217;s classpath and select Guice as your <SPAN style=\"FONT-FAMILY: Courier New\">ObjectFactory<\/SPAN> implementation in your <SPAN style=\"FONT-FAMILY: Courier New\">struts.xml<\/SPAN> file:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">&lt;constant name=&#8221;struts.objectFactory&#8221; value=&#8221;guice&#8221; \/&gt;<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Guice will inject all of your Struts 2 objects including actions and interceptors. You can even scope your actions. You can optionally specify a <SPAN style=\"FONT-FAMILY: Courier New\">Module<\/SPAN> for Guice to install in your <SPAN style=\"FONT-FAMILY: Courier New\">struts.xml<\/SPAN> file:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">&lt;constant name=&#8221;guice.module&#8221; value=&#8221;mypackage.MyModule&#8221;\/&gt;<BR><BR><\/SPAN><\/DIV><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">If all of your bindings are implicit, you can get away without defining a module at all.<BR><\/DIV><br \/>\n<H2>A Counting Example<\/H2><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Say for example that we want to count the number of requests in a session. Define a <SPAN style=\"FONT-FAMILY: Courier New\">Counter<\/SPAN> object which will live on the session:<BR><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">@SessionScoped<BR>public class Counter {<BR><BR>&nbsp; int count = 0;<BR><BR>&nbsp; \/** Increments the count and returns the new value. *\/<BR>&nbsp; public synchronized int increment() {<BR>&nbsp;&nbsp;&nbsp; return count++;<BR>&nbsp; }<BR>}<BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Next, we can inject our counter into an action:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">public class Count {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; final Counter counter;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; @Inject<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public Count(Counter counter) {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; this.counter = counter;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public String execute() {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; return SUCCESS;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; public int getCount() {<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; return counter.increment();<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; }<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">}<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">Then create a mapping for our action in our struts.xml file:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px; FONT-FAMILY: Courier New\">&lt;action name=&#8221;Count&#8221;<BR>&nbsp;&nbsp;&nbsp; class=&#8221;mypackage.Count&#8221;&gt;<BR>&nbsp; &lt;result&gt;\/WEB-INF\/Counter.jsp&lt;\/result&gt;<BR>&lt;\/action&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">And a JSP to render the result:<BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><BR><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\"><SPAN style=\"FONT-FAMILY: Courier New\">&lt;%@ taglib prefix=&#8221;s&#8221; uri=&#8221;\/struts-tags&#8221; %&gt;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&lt;html&gt;&nbsp;&nbsp; <\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; &lt;body&gt;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; &lt;h1&gt;Counter Example&lt;\/h1&gt;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp; &lt;h3&gt;&lt;b&gt;Hits in this session:&lt;\/b&gt;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;s:property value=&#8221;count&#8221;\/&gt;&lt;\/h3&gt;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&nbsp; &lt;\/body&gt;<\/SPAN><BR style=\"FONT-FAMILY: Courier New\"><SPAN style=\"FONT-FAMILY: Courier New\">&lt;\/html&gt;<\/SPAN><BR><\/DIV><BR><\/DIV><br \/>\n<DIV style=\"MARGIN-LEFT: 40px\">We actually made this example more complicated than necessary in an attempt to illustrate more concepts. In reality, we could have done away with the separate <SPAN style=\"FONT-FAMILY: Courier New\">Counter<\/SPAN> object and applied <SPAN style=\"FONT-FAMILY: Courier New\">@SessionScoped<\/SPAN> to our action directly.<BR><\/DIV><br \/>\n<H1>JMX Integration<BR><\/H1><br \/>\n<P style=\"MARGIN-LEFT: 40px\">See <A title=com.google.inject.tools.jmx style=\"FONT-FAMILY: Courier New\" href=\"http:\/\/google-guice.googlecode.com\/svn\/trunk\/javadoc\/com\/google\/inject\/tools\/jmx\/package-summary.html\">com.google.inject.tools.jmx<\/A>.<BR><\/P><br \/>\n<H1>Appendix: How the Injector resolves injection requests<\/H1><br \/>\n<P style=\"MARGIN-LEFT: 40px\">The injector&#8217;s process of resolving an injection request depends on the bindings that have been made and the annotations found on the types involved.&nbsp; Here is a summary of how an injection request is resolved:<\/P><br \/>\n<DIV style=\"MARGIN-LEFT: 80px\"><BR><\/DIV><br \/>\n<OL style=\"MARGIN-LEFT: 80px\"><br \/>\n<LI>Observe the Java type and the optional &#8220;binding annotation&#8221; of the element to be injected. If the type is <SPAN style=\"FONT-FAMILY: Courier New\">com.google.inject.Provider&lt;T&gt;<\/SPAN>, perform resolution for the type indicated by <SPAN style=\"FONT-FAMILY: Courier New\">T<\/SPAN> instead.&nbsp; Find a binding for this (type, annotation) pair. If none, skip to #4.<br \/>\n<LI>Follow transitive bindings. If this binding links to another binding, follow this edge and check again, repeating until we reach a binding which does not link to any other binding. We are now at the most specific explicit binding for this injection request.<br \/>\n<LI>If this binding specifies an instance or a <SPAN style=\"FONT-FAMILY: Courier New\">Provider<\/SPAN> instance, we&#8217;re done; use this to fulfill the request.<br \/>\n<LI>If, at this point, the injection request used an annotation type or value, we have failed and we produce an error.<BR><br \/>\n<LI>Otherwise examine the Java type for this binding; if an <SPAN style=\"FONT-FAMILY: Courier New\">@ImplementedBy<\/SPAN> annotation is found, instantiate the referenced type.&nbsp; If a <SPAN style=\"FONT-FAMILY: Courier New\">@ProvidedBy<\/SPAN> annotation is found, instantiate the referenced provider and use it to obtain the desired object. Otherwise attempt to instantiate the type itself.<\/LI><\/OL><br \/>\n<DIV><\/DIV><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Java on GuiceGuice 1.0 User&#8217;s Guide Guice (pronounced &#8220;juice&#8221;) is an ultra-lightweight, next-generation dependency injection container for Java 5 and later. Introduction The enterprise Java community exerts a lot of effort toward wiring objects together. How does your web application get access to a middle tier service, or your service to the logged in user &hellip; <a href=\"https:\/\/www.strongd.net\/?p=487\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Java on Guice<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[107],"class_list":["post-487","post","type-post","status-publish","format-standard","hentry","category-java","tag-guice"],"_links":{"self":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/487","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=487"}],"version-history":[{"count":1,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/487\/revisions"}],"predecessor-version":[{"id":885,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/487\/revisions\/885"}],"wp:attachment":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=487"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=487"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=487"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}