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