KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > example > ClientServiceWithGuice


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.AbstractModule;
20 import com.google.inject.CreationException;
21 import com.google.inject.Guice;
22 import com.google.inject.Inject;
23 import com.google.inject.Injector;
24 import com.google.inject.Scopes;
25 import static junit.framework.Assert.assertTrue;
26
27 /**
28  * @author crazybob@google.com (Bob Lee)
29  */

30 public class ClientServiceWithGuice {
31
32 // 48 lines
33

34 public interface Service {
35   void go();
36 }
37
38 public static class ServiceImpl implements Service {
39   public void go() {
40     // ...
41
}
42 }
43
44 public static class MyModule extends AbstractModule {
45   protected void configure() {
46     bind(Service.class).to(ServiceImpl.class).in(Scopes.SINGLETON);
47   }
48 }
49
50 public static class Client {
51
52   private final Service service;
53
54   @Inject
55   public Client(Service service) {
56     this.service = service;
57   }
58
59   public void go() {
60     service.go();
61   }
62 }
63
64 public void testClient() {
65   MockService mock = new MockService();
66   Client client = new Client(mock);
67   client.go();
68   assertTrue(mock.isGone());
69 }
70
71 public static class MockService implements Service {
72
73   private boolean gone = false;
74
75   public void go() {
76     gone = true;
77   }
78
79   public boolean isGone() {
80     return gone;
81   }
82 }
83
84 public static void main(String JavaDoc[] args) throws CreationException {
85   new ClientServiceWithGuice().testClient();
86   Injector injector = Guice.createInjector(new MyModule());
87   Client client = injector.getInstance(Client.class);
88 }
89 }
90
Popular Tags