001 /*****************************************************************************
002 * Copyright (C) PicoContainer Organization. All rights reserved. *
003 * ------------------------------------------------------------------------- *
004 * The software in this package is published under the terms of the BSD *
005 * style license a copy of which has been included with this distribution in *
006 * the LICENSE.txt file. *
007 * *
008 * Original code by *
009 *****************************************************************************/
010 package org.picocontainer.injectors;
011
012 import org.picocontainer.ComponentAdapter;
013 import org.picocontainer.ComponentMonitor;
014 import org.picocontainer.LifecycleStrategy;
015 import org.picocontainer.Parameter;
016 import org.picocontainer.PicoCompositionException;
017 import java.util.Properties;
018 import static org.picocontainer.Characteristics.immutable;
019
020 /**
021 * A {@link org.picocontainer.InjectionFactory} for named fields.
022 *
023 * Use like so: pico.as(injectionFieldNames("field1", "field2")).addComponent(...)
024 *
025 * The factory creates {@link TypedFieldInjector}.
026 *
027 * @author Paul Hammant
028 */
029 @SuppressWarnings("serial")
030 public class TypedFieldInjection extends AbstractInjectionFactory {
031
032 private static final String INJECTION_FIELD_TYPES = "injectionFieldTypes";
033
034 public <T> ComponentAdapter<T> createComponentAdapter(ComponentMonitor monitor,
035 LifecycleStrategy lifecycleStrategy,
036 Properties componentProperties,
037 Object componentKey,
038 Class<T> componentImplementation,
039 Parameter... parameters) throws PicoCompositionException {
040 String fieldTypes = (String) componentProperties.remove(INJECTION_FIELD_TYPES);
041 if (fieldTypes == null) {
042 fieldTypes = "";
043 }
044 return wrapLifeCycle(monitor.newInjector(new TypedFieldInjector(componentKey, componentImplementation, parameters, monitor,
045 fieldTypes)), lifecycleStrategy);
046 }
047
048 public static Properties injectionFieldTypes(String... fieldTypes) {
049 StringBuilder sb = new StringBuilder();
050 for (int i = 0; i < fieldTypes.length; i++) {
051 sb.append(" ").append(fieldTypes[i]);
052 }
053 return immutable(INJECTION_FIELD_TYPES, sb.toString().trim());
054 }
055
056 }