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 *****************************************************************************/
010package org.picocontainer.injectors;
011
012import org.picocontainer.ComponentAdapter;
013import org.picocontainer.ComponentMonitor;
014import org.picocontainer.LifecycleStrategy;
015import org.picocontainer.Parameter;
016import org.picocontainer.PicoCompositionException;
017import java.util.Properties;
018import 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")
030public 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}