Example usage for org.springframework.beans.factory.support GenericBeanDefinition setAutowireMode

List of usage examples for org.springframework.beans.factory.support GenericBeanDefinition setAutowireMode

Introduction

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

Prototype

public void setAutowireMode(int autowireMode) 

Source Link

Document

Set the autowire mode.

Usage

From source file:darks.orm.spring.MapperClassDefinitionScanner.java

private void processBeanDefinition(GenericBeanDefinition definition) {
    definition.getPropertyValues().add("sqlMapInterface", definition.getBeanClassName());
    definition.setBeanClass(SqlMapFactoryBean.class);
    definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
}

From source file:com.github.steveash.spring.WiringFactoryBeanFactoryPostProcessor.java

private void addPrototypeDef(ConfigurableListableBeanFactory beanFactory, String beanDefName,
        Class<?> protoBeanClass) {
    String beanName = getPrototypeBeanNameFromBeanClass(protoBeanClass);
    if (beanFactory.containsBeanDefinition(beanName)) {
        throw new BeanDefinitionValidationException("Trying to register a bean definition for a synthetic "
                + "prototype bean with name " + beanName + " due to the bean factory of name " + beanDefName
                + " but a bean with this name already exists!");
    }/*from  w ww  . j  a v a2s. c  o  m*/

    GenericBeanDefinition protoBean = new GenericBeanDefinition();
    protoBean.setLazyInit(true);
    protoBean.setBeanClass(protoBeanClass);
    protoBean.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    protoBean.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    protoBean.setBeanClassName(protoBeanClass.getName());

    log.debug("Dynamically adding prototype bean {} from factory {}", beanName, beanDefName);
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    registry.registerBeanDefinition(beanName, protoBean);
}

From source file:com.fitbur.jestify.junit.spring.IntegrationTestReifier.java

@Override
public Object reifyCut(CutDescriptor cutDescriptor, Object[] arguments) {
    return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        try {/*  w  w w .  j av  a  2s. c o m*/
            Cut cut = cutDescriptor.getCut();
            Field field = cutDescriptor.getField();
            Type fieldType = field.getGenericType();
            String fieldName = field.getName();

            field.setAccessible(true);

            Constructor<?> constructor = cutDescriptor.getConstructor();
            constructor.setAccessible(true);

            ResolvableType resolver = ResolvableType.forType(fieldType);

            Class rawType;

            if (resolver.hasGenerics()) {
                if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
                    rawType = resolver.getRawClass();
                } else {
                    rawType = resolver.resolve();
                }
            } else {
                rawType = resolver.resolve();
            }

            Module module = testInstance.getClass().getDeclaredAnnotation(Module.class);

            GenericBeanDefinition bean = new GenericBeanDefinition();
            bean.setBeanClass(rawType);
            bean.setAutowireCandidate(false);
            bean.setScope(SCOPE_PROTOTYPE);
            bean.setPrimary(true);
            bean.setLazyInit(true);
            bean.setRole(RootBeanDefinition.ROLE_APPLICATION);
            bean.setAutowireMode(RootBeanDefinition.AUTOWIRE_NO);
            appContext.registerBeanDefinition(fieldName, bean);
            if (module != null) {
                appContext.register(module.value());
            }
            appContext.refresh();

            Object instance = appContext.getBean(fieldName, arguments);

            if (cut.value()) {
                instance = spy(instance);
            }

            field.set(testInstance, instance);

            return instance;
        } catch (SecurityException | IllegalAccessException | IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
    });
}

From source file:com.fitbur.testify.di.spring.SpringServiceLocator.java

@Override
public void addService(ServiceDescriptor descriptor) {
    checkState(!context.containsBeanDefinition(descriptor.getName()),
            "Service with the name '%s' already exists.", descriptor.getName());

    GenericBeanDefinition bean = new GenericBeanDefinition();
    bean.setBeanClass(descriptor.getType());
    bean.setAutowireCandidate(descriptor.getDiscoverable());
    bean.setPrimary(descriptor.getPrimary());
    bean.setLazyInit(descriptor.getLazy());
    bean.setRole(ROLE_APPLICATION);//from  ww  w  .  j a v  a 2 s .  c om

    if (descriptor.getInjectable()) {
        bean.setAutowireMode(AUTOWIRE_CONSTRUCTOR);
    } else {
        bean.setAutowireMode(AUTOWIRE_NO);
        ConstructorArgumentValues values = new ConstructorArgumentValues();

        Object[] arguments = descriptor.getArguments();
        for (int i = 0; i < arguments.length; i++) {
            Object arg = arguments[i];

            if (arg == null) {
                //TODO: warn user that the argument was not specified and there
                //for the real instance will be injected.
                continue;
            }

            values.addIndexedArgumentValue(i, arg);
        }

        bean.setConstructorArgumentValues(values);
    }

    ServiceScope scope = descriptor.getScope();
    switch (scope) {
    case PROTOTYPE:
        bean.setScope("prototype");
        break;
    case SINGLETON:
        bean.setScope("singleton");
        break;
    case REQUEST:
        bean.setScope("request");
        break;
    case SESSION:
        bean.setScope("session");
        break;
    case APPLICATION:
        bean.setScope("application");
        break;
    default:
        checkState(false, "Scope '{}' is not supported by Spring IoC.", scope.name());

    }
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
    beanFactory.registerBeanDefinition(descriptor.getName(), bean);
}

From source file:org.romaz.spring.scripting.ext.ExtScriptBeanDefinitionParser.java

/**
 * Parses the dynamic object element and returns the resulting bean definition.
 * Registers a {@link ScriptFactoryPostProcessor} if needed.
 *//*from w w w.  j ava 2  s .c  o m*/
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    // Resolve the script source.
    String value = resolveScriptSource(element, parserContext.getReaderContext());
    if (value == null) {
        return null;
    }

    // Set up infrastructure.
    LangNamespaceUtils.registerScriptFactoryPostProcessorIfNecessary(parserContext.getRegistry());

    // Create script factory bean definition.
    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClassName(this.scriptFactoryClassName);
    bd.setSource(parserContext.extractSource(element));

    // Determine bean scope.
    String scope = element.getAttribute(SCOPE_ATTRIBUTE);
    if (StringUtils.hasLength(scope)) {
        bd.setScope(scope);
    }

    // Determine autowire mode.
    String autowire = element.getAttribute(AUTOWIRE_ATTRIBUTE);
    int autowireMode = parserContext.getDelegate().getAutowireMode(autowire);
    // Only "byType" and "byName" supported, but maybe other default inherited...
    if (autowireMode == GenericBeanDefinition.AUTOWIRE_AUTODETECT) {
        autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE;
    } else if (autowireMode == GenericBeanDefinition.AUTOWIRE_CONSTRUCTOR) {
        autowireMode = GenericBeanDefinition.AUTOWIRE_NO;
    }
    bd.setAutowireMode(autowireMode);

    // Determine dependency check setting.
    String dependencyCheck = element.getAttribute(DEPENDENCY_CHECK_ATTRIBUTE);
    bd.setDependencyCheck(parserContext.getDelegate().getDependencyCheck(dependencyCheck));

    // Retrieve the defaults for bean definitions within this parser context
    BeanDefinitionDefaults beanDefinitionDefaults = parserContext.getDelegate().getBeanDefinitionDefaults();

    // Determine init method and destroy method.
    String initMethod = element.getAttribute(INIT_METHOD_ATTRIBUTE);
    if (StringUtils.hasLength(initMethod)) {
        bd.setInitMethodName(initMethod);
    } else if (beanDefinitionDefaults.getInitMethodName() != null) {
        bd.setInitMethodName(beanDefinitionDefaults.getInitMethodName());
    }

    String destroyMethod = element.getAttribute(DESTROY_METHOD_ATTRIBUTE);
    if (StringUtils.hasLength(destroyMethod)) {
        bd.setDestroyMethodName(destroyMethod);
    } else if (beanDefinitionDefaults.getDestroyMethodName() != null) {
        bd.setDestroyMethodName(beanDefinitionDefaults.getDestroyMethodName());
    }

    // Attach any refresh metadata.
    String refreshCheckDelay = element.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
    if (StringUtils.hasText(refreshCheckDelay)) {
        bd.setAttribute(ScriptFactoryPostProcessor.REFRESH_CHECK_DELAY_ATTRIBUTE, new Long(refreshCheckDelay));
    }

    // Add constructor arguments.
    ConstructorArgumentValues cav = bd.getConstructorArgumentValues();
    int constructorArgNum = 0;
    cav.addIndexedArgumentValue(constructorArgNum++, value);
    if (element.hasAttribute(SCRIPT_INTERFACES_ATTRIBUTE)) {
        cav.addIndexedArgumentValue(constructorArgNum++, element.getAttribute(SCRIPT_INTERFACES_ATTRIBUTE));
    }
    if (element.hasAttribute(SCRIPT_CONFIG_ATTRIBUTE)) {
        cav.addIndexedArgumentValue(constructorArgNum++,
                new RuntimeBeanReference(element.getAttribute(SCRIPT_CONFIG_ATTRIBUTE)));
    }
    // Add any property definitions that need adding.
    parserContext.getDelegate().parsePropertyElements(element, bd);

    return bd;
}

From source file:com.comstar.mars.env.EnvClassPathMapperScanner.java

/**
 * Calls the parent search that will search and register all the candidates.
 * Then the registered objects are post processed to set them as
 * MapperFactoryBeans//from  w w w . j a v a2  s .c o  m
 */
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

    if (beanDefinitions.isEmpty()) {
        logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages)
                + "' package. Please check your configuration.");
    } else {
        for (BeanDefinitionHolder holder : beanDefinitions) {
            GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();

            if (logger.isDebugEnabled()) {
                logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '"
                        + definition.getBeanClassName() + "' mapperInterface");
            }

            // the mapper interface is the original class of the bean
            // but, the actual class of the bean is MapperFactoryBean
            definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
            definition.setBeanClass(EnvMapperFactoryBean.class);

            boolean explicitFactoryUsed = false;
            if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
                definition.getPropertyValues().add("sqlSessionFactory",
                        new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
                explicitFactoryUsed = true;
            } else if (this.sqlSessionFactory != null) {
                definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
                explicitFactoryUsed = true;
            }

            if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
                if (explicitFactoryUsed) {
                    logger.warn(
                            "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
                }
                definition.getPropertyValues().add("sqlSessionTemplate",
                        new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
                explicitFactoryUsed = true;
            } else if (this.sqlSessionTemplate != null) {
                if (explicitFactoryUsed) {
                    logger.warn(
                            "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
                }
                definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
                explicitFactoryUsed = true;
            }

            if (!explicitFactoryUsed) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Enabling autowire by type for MapperFactoryBean with name '"
                            + holder.getBeanName() + "'.");
                }
                definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
            }
        }
    }

    return beanDefinitions;
}

From source file:org.mybatis.spring.mapper.ClassPathMapperScanner.java

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
    GenericBeanDefinition definition;
    for (BeanDefinitionHolder holder : beanDefinitions) {
        definition = (GenericBeanDefinition) holder.getBeanDefinition();

        if (logger.isDebugEnabled()) {
            logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '"
                    + definition.getBeanClassName() + "' mapperInterface");
        }//from w w  w. ja  v a2s .c om

        // the mapper interface is the original class of the bean
        // but, the actual class of the bean is MapperFactoryBean
        definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
        definition.setBeanClass(this.mapperFactoryBean.getClass());

        definition.getPropertyValues().add("addToConfig", this.addToConfig);

        boolean explicitFactoryUsed = false;
        if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
            definition.getPropertyValues().add("sqlSessionFactory",
                    new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
            explicitFactoryUsed = true;
        } else if (this.sqlSessionFactory != null) {
            definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
            explicitFactoryUsed = true;
        }

        if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
            if (explicitFactoryUsed) {
                logger.warn(
                        "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
            }
            definition.getPropertyValues().add("sqlSessionTemplate",
                    new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
            explicitFactoryUsed = true;
        } else if (this.sqlSessionTemplate != null) {
            if (explicitFactoryUsed) {
                logger.warn(
                        "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
            }
            definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
            explicitFactoryUsed = true;
        }

        if (!explicitFactoryUsed) {
            if (logger.isDebugEnabled()) {
                logger.debug("Enabling autowire by type for MapperFactoryBean with name '"
                        + holder.getBeanName() + "'.");
            }
            definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        }
    }
}

From source file:framework.generic.mybatis.ClassPathMapperScanner.java

/**
 * Calls the parent search that will search and register all the candidates.
 * Then the registered objects are post processed to set them as
 * MapperFactoryBeans// www.  ja  v  a  2  s.  c o m
 */
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
    if (beanDefinitions.isEmpty()) {
        logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages)
                + "' package. Please check your configuration.");
    } else {
        for (BeanDefinitionHolder holder : beanDefinitions) {
            GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();

            if (logger.isDebugEnabled()) {
                logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '"
                        + definition.getBeanClassName() + "' mapperInterface");
            }

            // the mapper interface is the original class of the bean
            // but, the actual class of the bean is MapperFactoryBean
            definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
            definition.setBeanClass(MapperFactoryBean.class);
            // definition.setBeanClass(ExecutorFactoryBean.class);
            definition.getPropertyValues().add("executor", this.executor);
            definition.getPropertyValues().add("addToConfig", this.addToConfig);
            boolean explicitFactoryUsed = false;
            if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
                definition.getPropertyValues().add("sqlSessionFactory",
                        new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
                explicitFactoryUsed = true;
            } else if (this.sqlSessionFactory != null) {
                definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
                explicitFactoryUsed = true;
            }

            if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
                if (explicitFactoryUsed) {
                    logger.warn(
                            "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
                }
                definition.getPropertyValues().add("sqlSessionTemplate",
                        new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
                explicitFactoryUsed = true;
            } else if (this.sqlSessionTemplate != null) {
                if (explicitFactoryUsed) {
                    logger.warn(
                            "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
                }
                definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
                explicitFactoryUsed = true;
            }

            if (!explicitFactoryUsed) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Enabling autowire by type for MapperFactoryBean with name '"
                            + holder.getBeanName() + "'.");
                }
                definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
            }
        }
    }

    return beanDefinitions;
}