1 /** 2 * Copyright (C) 2006 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.inject.example; 18 19 import static junit.framework.Assert.assertTrue; 20 21 import com.google.inject.AbstractModule; 22 import com.google.inject.CreationException; 23 import com.google.inject.Guice; 24 import com.google.inject.Inject; 25 import com.google.inject.Injector; 26 import com.google.inject.Scopes; 27 28 /** 29 * @author crazybob (at) google.com (Bob Lee) 30 */ 31 public class ClientServiceWithGuice { 32 33 // 48 lines 34 35 public interface Service { 36 void go(); 37 } 38 39 public static class ServiceImpl implements Service { 40 public void go() { 41 // ... 42 } 43 } 44 45 public static class MyModule extends AbstractModule { 46 protected void configure() { 47 bind(Service.class).to(ServiceImpl.class).in(Scopes.SINGLETON); 48 } 49 } 50 51 public static class Client { 52 53 private final Service service; 54 55 @Inject 56 public Client(Service service) { 57 this.service = service; 58 } 59 60 public void go() { 61 service.go(); 62 } 63 } 64 65 public void testClient() { 66 MockService mock = new MockService(); 67 Client client = new Client(mock); 68 client.go(); 69 assertTrue(mock.isGone()); 70 } 71 72 public static class MockService implements Service { 73 74 private boolean gone = false; 75 76 public void go() { 77 gone = true; 78 } 79 80 public boolean isGone() { 81 return gone; 82 } 83 } 84 85 public static void main(String[] args) throws CreationException { 86 new ClientServiceWithGuice().testClient(); 87 Injector injector = Guice.createInjector(new MyModule()); 88 Client client = injector.getInstance(Client.class); 89 } 90 } 91