KickJava   Java API By Example, From Geeks To Geeks.

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


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.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 /**
28  * @author crazybob@google.com (Bob Lee)
29  */

30 public class ClientServiceWithGuiceDefaults {
31
32 // 44 lines
33

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     // ...
43
}
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 JavaDoc[] 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