/*
 * Copyright 2006 digiZen Studio, LLC
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.digizen.commons.spring;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * @author Jing Xue
 * @version $Revision: $ $Author: $
 */
public class AdviceSkippingInjector implements BeanPostProcessor {
    private static final Logger LOG = Logger.getLogger(AdviceSkippingInjector.class);
    
    private Map<String, String> _beanProperties;

    /***/
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        String propName = _beanProperties.get(beanName);
        if (propName != null) {
            Object targetBean = bean;
            while (targetBean instanceof Advised) {
                try {
                    targetBean = ((Advised)targetBean).getTargetSource().getTarget();
                } catch (Exception e) {
                    throw new BeanInitializationException("Unable to resolve target", e);
                }
            }

            LOG.debug("Recursive injecting: beanname: " + beanName + "; property: "
                      + propName + "; bean class: " + targetBean.getClass()
                      + "; injected with: " + bean.getClass());
            new BeanWrapperImpl(targetBean).setPropertyValue(propName, bean);
        }
        return bean;
    }

    /***/
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    public Map<String, String> getBeanProperties() {
        return _beanProperties;
    }

    public void setBeanProperties(Map<String, String> names) {
        _beanProperties = names;
    }
}

