• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.name;
18 
19 import com.google.inject.Binder;
20 import com.google.inject.Key;
21 import java.util.Enumeration;
22 import java.util.Map;
23 import java.util.Properties;
24 
25 /**
26  * Utility methods for use with {@code @}{@link Named}.
27  *
28  * @author crazybob@google.com (Bob Lee)
29  */
30 public class Names {
31 
Names()32   private Names() {}
33 
34   /** Creates a {@link Named} annotation with {@code name} as the value. */
named(String name)35   public static Named named(String name) {
36     return new NamedImpl(name);
37   }
38 
39   /** Creates a constant binding to {@code @Named(key)} for each entry in {@code properties}. */
bindProperties(Binder binder, Map<String, String> properties)40   public static void bindProperties(Binder binder, Map<String, String> properties) {
41     binder = binder.skipSources(Names.class);
42     for (Map.Entry<String, String> entry : properties.entrySet()) {
43       String key = entry.getKey();
44       String value = entry.getValue();
45       binder.bind(Key.get(String.class, new NamedImpl(key))).toInstance(value);
46     }
47   }
48 
49   /**
50    * Creates a constant binding to {@code @Named(key)} for each property. This method binds all
51    * properties including those inherited from {@link Properties#defaults defaults}.
52    */
bindProperties(Binder binder, Properties properties)53   public static void bindProperties(Binder binder, Properties properties) {
54     binder = binder.skipSources(Names.class);
55 
56     // use enumeration to include the default properties
57     for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) {
58       String propertyName = (String) e.nextElement();
59       String value = properties.getProperty(propertyName);
60       binder.bind(Key.get(String.class, new NamedImpl(propertyName))).toInstance(value);
61     }
62   }
63 }
64