Example usage for org.springframework.beans.factory.support InstantiationStrategy InstantiationStrategy

List of usage examples for org.springframework.beans.factory.support InstantiationStrategy InstantiationStrategy

Introduction

In this page you can find the example usage for org.springframework.beans.factory.support InstantiationStrategy InstantiationStrategy.

Prototype

InstantiationStrategy

Source Link

Usage

From source file:co.paralleluniverse.common.spring.SpringContainerHelper.java

/**
 * adds hooks to capture autowired constructor args and add them as dependencies
 *
 * @return// w  ww  . j  av a  2s  .co m
 */
private static DefaultListableBeanFactory createBeanFactory() {
    return new DefaultListableBeanFactory() {
        {
            final InstantiationStrategy is = getInstantiationStrategy();
            setInstantiationStrategy(new InstantiationStrategy() {
                @Override
                public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner)
                        throws BeansException {
                    return is.instantiate(beanDefinition, beanName, owner);
                }

                @Override
                public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner,
                        Constructor<?> ctor, Object[] args) throws BeansException {
                    final Object bean = is.instantiate(beanDefinition, beanName, owner, ctor, args);
                    addDependencies(bean, args);
                    return bean;
                }

                @Override
                public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner,
                        Object factoryBean, Method factoryMethod, Object[] args) throws BeansException {
                    final Object bean = is.instantiate(beanDefinition, beanName, owner, factoryBean,
                            factoryMethod, args);
                    addDependencies(bean, args);
                    return bean;
                }
            });
        }

        private void addDependencies(Object bean, Object[] args) {
            if (bean instanceof Service) {
                for (Object arg : args) {
                    if (arg instanceof Service) {
                        ((Service) arg).addDependedBy((Service) bean);
                        ((Service) bean).addDependsOn((Service) arg);
                    }
                }
            }
        }
    };
}