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