001    // Copyright 2007 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.hivemind.service.impl;
016    
017    import org.apache.commons.logging.Log;
018    import org.apache.commons.logging.LogFactory;
019    import org.apache.hivemind.internal.RegistryInfrastructure;
020    import org.apache.hivemind.service.AutowiringStrategy;
021    import org.apache.hivemind.util.PropertyUtils;
022    
023    /**
024     * Implementation of {@link AutowiringStrategy} that searches for
025     * a matching service by the type of a property. 
026     * 
027     * @author Achim Huegen
028     */
029    public class AutowiringByTypeStrategy implements AutowiringStrategy
030    {
031        private static final Log LOG = LogFactory.getLog(AutowiringByTypeStrategy.class);
032    
033        public boolean autowireProperty(RegistryInfrastructure registry, Object target, String propertyName)
034        {
035            Class propertyType = PropertyUtils.getPropertyType(target, propertyName);
036    
037            // search for a property with an interface that matches the property type
038            if (registry.containsService(propertyType, null))
039            {
040                Object collaboratingService = registry.getService(propertyType, null);
041                PropertyUtils.write(target, propertyName, collaboratingService);
042    
043                if (LOG.isDebugEnabled())
044                {
045                    LOG.debug("Autowired property " + propertyName + " by type to " + collaboratingService);
046                }
047                return true;
048            } else {
049                return false;
050            }
051        }
052    
053    }