01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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: */package com.google.inject.example;
16:
17: import com.google.inject.Inject;
18: import com.google.inject.CreationException;
19: import com.google.inject.Injector;
20: import com.google.inject.Guice;
21: import com.google.inject.ImplementedBy;
22: import com.google.inject.Singleton;
23: import junit.framework.Assert;
24:
25: /**
26: * @author crazybob@google.com (Bob Lee)
27: */
28: public class ClientServiceWithGuiceDefaults {
29:
30: // 44 lines
31:
32: @ImplementedBy(ServiceImpl.class)
33: public interface Service {
34: void go();
35: }
36:
37: @Singleton
38: public static class ServiceImpl implements
39: ClientServiceWithGuiceDefaults.Service {
40: public void go() {
41: // ...
42: }
43: }
44:
45: public static class Client {
46:
47: private final Service service;
48:
49: @Inject
50: public Client(Service service) {
51: this .service = service;
52: }
53:
54: public void go() {
55: service.go();
56: }
57: }
58:
59: public void testClient() {
60: MockService mock = new MockService();
61: Client client = new Client(mock);
62: client.go();
63: Assert.assertTrue(mock.isGone());
64: }
65:
66: public static class MockService implements Service {
67:
68: private boolean gone = false;
69:
70: public void go() {
71: gone = true;
72: }
73:
74: public boolean isGone() {
75: return gone;
76: }
77: }
78:
79: public static void main(String[] args) throws CreationException {
80: new ClientServiceWithGuiceDefaults().testClient();
81: Injector injector = Guice.createInjector();
82: Client client = injector.getProvider(Client.class).get();
83: }
84: }
|