Package org.internna.iwebmvc.spring.util

Source Code of org.internna.iwebmvc.spring.util.TransientFieldsInjector

package org.internna.iwebmvc.spring.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;

/**
* Injects fields after serialization.
*
* @author Jose Noheda
* @since 2.0
*
*/
public final class TransientFieldsInjector implements ApplicationContextAware {

  private static ApplicationContext applicationContext;
  private static final Log logger = LogFactory.getLog(TransientFieldsInjector.class);

  @Override public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
    TransientFieldsInjector.applicationContext = appCtx;
  }

  @SuppressWarnings("unchecked")
  public static void inject (Object bean, String... properties) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    for (String propertyName : properties) {
      PropertyDescriptor property = BeanUtils.getPropertyDescriptor(bean.getClass(), propertyName);
      Class<?> propertyClass = property.getPropertyType();
      Map<String, Object> deps = applicationContext.getBeansOfType(propertyClass);
            if (!CollectionUtils.isEmpty(deps)) {
                if (deps.size() != 1) logger.warn("More than one bean of type [" + propertyClass + "] in context. Unexpected errors may happen with unserialized bean!");
                Object dependency = deps.entrySet().iterator().next().getValue();
                property.getWriteMethod().invoke(bean, dependency);
            }
    }
  }

}
TOP

Related Classes of org.internna.iwebmvc.spring.util.TransientFieldsInjector

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.