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.name;
16:
17: import com.google.inject.Binder;
18: import com.google.inject.Key;
19: import com.google.inject.spi.SourceProviders;
20: import com.google.inject.spi.SourceProvider;
21: import java.util.Map;
22: import java.util.Properties;
23:
24: /**
25: * Utility methods for use with {@code @}{@link Named}.
26: *
27: * @author crazybob@google.com (Bob Lee)
28: */
29: public class Names {
30:
31: private Names() {
32: }
33:
34: static {
35: SourceProviders.skip(Names.class);
36: }
37:
38: /**
39: * Creates a {@link Named} annotation with {@code name} as the value.
40: */
41: public static Named named(String name) {
42: return new NamedImpl(name);
43: }
44:
45: /**
46: * Creates a constant binding to {@code @Named(key)} for each property.
47: */
48: public static void bindProperties(final Binder binder,
49: final Map<String, String> properties) {
50: SourceProviders.withDefault(new SimpleSourceProvider(
51: SourceProviders.defaultSource()), new Runnable() {
52: public void run() {
53: for (Map.Entry<String, String> entry : properties
54: .entrySet()) {
55: String key = entry.getKey();
56: String value = entry.getValue();
57: binder.bind(
58: Key.get(String.class, new NamedImpl(key)))
59: .toInstance(value);
60: }
61: }
62: });
63: }
64:
65: /**
66: * Creates a constant binding to {@code @Named(key)} for each property.
67: */
68: public static void bindProperties(final Binder binder,
69: final Properties properties) {
70: SourceProviders.withDefault(new SimpleSourceProvider(
71: SourceProviders.defaultSource()), new Runnable() {
72: public void run() {
73: for (Map.Entry<Object, Object> entry : properties
74: .entrySet()) {
75: String key = (String) entry.getKey();
76: String value = (String) entry.getValue();
77: binder.bind(
78: Key.get(String.class, new NamedImpl(key)))
79: .toInstance(value);
80: }
81: }
82: });
83: }
84:
85: static class SimpleSourceProvider implements SourceProvider {
86:
87: final Object source;
88:
89: SimpleSourceProvider(Object source) {
90: this .source = source;
91: }
92:
93: public Object source() {
94: return source;
95: }
96: }
97: }
|