Package org.jibeframework.core.service.impl

Source Code of org.jibeframework.core.service.impl.ManagedObjectFactoryImpl

package org.jibeframework.core.service.impl;

import java.lang.reflect.Constructor;

import org.jibeframework.core.JibeRuntimeException;
import org.jibeframework.core.service.ManagedObjectFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

/**
*
* @author dhalupa
*
*/
@Service
public class ManagedObjectFactoryImpl implements ManagedObjectFactory, BeanFactoryAware, InitializingBean {
  private static ManagedObjectFactory instance;
  AutowiredAnnotationBeanPostProcessor processor = new AutowiredAnnotationBeanPostProcessor();

  public static void injectDeps(Object object) {
    if (instance != null) {
      instance.injectDependencies(object);
    }
  }

  @SuppressWarnings("unchecked")
  public <T> T create(Class<T> clazz, Object... params) {
    T object = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    for (Constructor<?> constructor : constructors) {
      Class<?>[] parameterTypes = constructor.getParameterTypes();
      boolean match = true;
      if (!constructor.isVarArgs() && parameterTypes.length == params.length) {
        for (int i = 0; i < parameterTypes.length; i++) {
          if (params[i] != null) {
            if (!parameterTypes[i].isAssignableFrom(params[i].getClass())) {
              match = false;
              break;
            }

          }
        }
        if (match) {
          try {
            object = (T) constructor.newInstance(params);
            processor.processInjection(object);
          } catch (Exception e) {
            ReflectionUtils.handleReflectionException(e);
          }
        }

      }
    }
    if (object == null) {
      throw new JibeRuntimeException("Matching constructor was not found:" + clazz.getName());
    }
    return object;
  }

  public void injectDependencies(Object object) {
    processor.processInjection(object);
  }

  public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    processor.setBeanFactory(beanFactory);
  }

  public void afterPropertiesSet() throws Exception {
    instance = this;

  }

}
TOP

Related Classes of org.jibeframework.core.service.impl.ManagedObjectFactoryImpl

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.