Home | History | Annotate | Download | only in example
      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 com.google.inject.CreationException;
     20 import com.google.inject.Guice;
     21 import com.google.inject.ImplementedBy;
     22 import com.google.inject.Inject;
     23 import com.google.inject.Injector;
     24 import com.google.inject.Singleton;
     25 
     26 import junit.framework.Assert;
     27 
     28 /**
     29  * @author crazybob (at) google.com (Bob Lee)
     30  */
     31 public class ClientServiceWithGuiceDefaults {
     32 
     33 // 44 lines
     34 
     35 @ImplementedBy(ServiceImpl.class)
     36 public interface Service {
     37   void go();
     38 }
     39 
     40 @Singleton
     41 public static class ServiceImpl implements ClientServiceWithGuiceDefaults.Service {
     42   public void go() {
     43     // ...
     44   }
     45 }
     46 
     47 public static class Client {
     48 
     49   private final Service service;
     50 
     51   @Inject
     52   public Client(Service service) {
     53     this.service = service;
     54   }
     55 
     56   public void go() {
     57     service.go();
     58   }
     59 }
     60 
     61 public void testClient() {
     62   MockService mock = new MockService();
     63   Client client = new Client(mock);
     64   client.go();
     65   Assert.assertTrue(mock.isGone());
     66 }
     67 
     68 public static class MockService implements Service {
     69 
     70   private boolean gone = false;
     71 
     72   public void go() {
     73     gone = true;
     74   }
     75 
     76   public boolean isGone() {
     77     return gone;
     78   }
     79 }
     80 
     81 public static void main(String[] args) throws CreationException {
     82   new ClientServiceWithGuiceDefaults().testClient();
     83   Injector injector = Guice.createInjector();
     84   Client client = injector.getProvider(Client.class).get();
     85 }
     86 }
     87