1 16 17 package com.google.inject.example; 18 19 import com.google.inject.Inject; 20 import com.google.inject.CreationException; 21 import com.google.inject.Injector; 22 import com.google.inject.Guice; 23 import com.google.inject.ImplementedBy; 24 import com.google.inject.Singleton; 25 import junit.framework.Assert; 26 27 30 public class ClientServiceWithGuiceDefaults { 31 32 34 @ImplementedBy(ServiceImpl.class) 35 public interface Service { 36 void go(); 37 } 38 39 @Singleton 40 public static class ServiceImpl implements ClientServiceWithGuiceDefaults.Service { 41 public void go() { 42 } 44 } 45 46 public static class Client { 47 48 private final Service service; 49 50 @Inject 51 public Client(Service service) { 52 this.service = service; 53 } 54 55 public void go() { 56 service.go(); 57 } 58 } 59 60 public void testClient() { 61 MockService mock = new MockService(); 62 Client client = new Client(mock); 63 client.go(); 64 Assert.assertTrue(mock.isGone()); 65 } 66 67 public static class MockService implements Service { 68 69 private boolean gone = false; 70 71 public void go() { 72 gone = true; 73 } 74 75 public boolean isGone() { 76 return gone; 77 } 78 } 79 80 public static void main(String [] args) throws CreationException { 81 new ClientServiceWithGuiceDefaults().testClient(); 82 Injector injector = Guice.createInjector(); 83 Client client = injector.getProvider(Client.class).get(); 84 } 85 } 86 | Popular Tags |