Example usage for org.springframework.beans.factory.config BeanDefinition isAutowireCandidate

List of usage examples for org.springframework.beans.factory.config BeanDefinition isAutowireCandidate

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config BeanDefinition isAutowireCandidate.

Prototype

boolean isAutowireCandidate();

Source Link

Document

Return whether this bean is a candidate for getting autowired into some other bean.

Usage

From source file:ch.nydi.spring.context.support.PrimaryResolverListableBeanFactory.java

@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
    Assert.notNull(requiredType, "Required type must not be null");
    String[] beanNames = getBeanNamesForType(requiredType);
    String primaryCandidate = null;
    if (beanNames.length > 1) {
        final ArrayList<String> autowireCandidates = new ArrayList<String>();

        for (final String beanName : beanNames) {
            final BeanDefinition beanDefinition = getBeanDefinition(beanName);
            if (beanDefinition.isAutowireCandidate()) {
                autowireCandidates.add(beanName);
                if (beanDefinition.isPrimary()) {
                    primaryCandidate = beanName;
                }/*from   w  w w .j  a v a2  s.com*/
            }
        }
        if (autowireCandidates.size() > 0) {
            beanNames = autowireCandidates.toArray(new String[autowireCandidates.size()]);
        }
    }
    if (beanNames.length == 1) {
        return getBean(beanNames[0], requiredType);
    } else if (beanNames.length > 1) { // more than one bean defined, lookup primary candidate
        if (primaryCandidate != null) {
            return getBean(primaryCandidate, requiredType);
        }
        throw new NoSuchBeanDefinitionException(requiredType, "expected single bean but found "
                + beanNames.length + ": " + StringUtils.arrayToCommaDelimitedString(beanNames));
    } else if (beanNames.length == 0 && getParentBeanFactory() != null) {
        return getParentBeanFactory().getBean(requiredType);
    } else {
        throw new NoSuchBeanDefinitionException(requiredType, "expected single bean but found "
                + beanNames.length + ": " + StringUtils.arrayToCommaDelimitedString(beanNames));
    }
}

From source file:net.easysmarthouse.service.context.ProxiedResolverGenericXmlApplicationContext.java

@Override
public <T extends Object> T getBean(Class<T> requiredType) throws BeansException {
    Assert.notNull(requiredType, "Required type must not be null");
    String[] beanNames = getBeanNamesForType(requiredType);
    String primaryCandidate = null;

    if (beanNames.length > 1) {
        ArrayList<String> autowireCandidates = new ArrayList<String>();

        for (String beanName : beanNames) {
            BeanDefinition beanDefinition = getBeanDefinition(beanName);
            if (beanDefinition.isAutowireCandidate()) {
                autowireCandidates.add(beanName);
                if (beanDefinition.isPrimary()) {
                    primaryCandidate = beanName;
                }/*from w  w  w  . j  a  v  a2s.  co m*/
            }
        }

        for (String autowireCandidate : autowireCandidates) {
            if (autowireCandidates.contains(autowireCandidate + "Proxied")) {
                primaryCandidate = autowireCandidate;
            }
        }

        if (autowireCandidates.size() > 0) {
            beanNames = autowireCandidates.toArray(new String[autowireCandidates.size()]);
        }
    }

    if (beanNames.length == 1) {
        return getBean(beanNames[0], requiredType);

    } else if (beanNames.length > 1) {
        // more than one bean defined, lookup primary candidate
        if (primaryCandidate != null) {
            return getBean(primaryCandidate, requiredType);
        }
        throw new NoSuchBeanDefinitionException(requiredType, "expected single bean but found "
                + beanNames.length + ": " + StringUtils.arrayToCommaDelimitedString(beanNames));

    } else if (beanNames.length == 0 && getParentBeanFactory() != null) {
        return getParentBeanFactory().getBean(requiredType);

    } else {
        throw new NoSuchBeanDefinitionException(requiredType, "expected single bean but found "
                + beanNames.length + ": " + StringUtils.arrayToCommaDelimitedString(beanNames));

    }
}

From source file:org.spring.guice.module.SpringModule.java

@Override
public void configure(Binder binder) {
    for (String name : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition definition = beanFactory.getBeanDefinition(name);
        if (definition.isAutowireCandidate()
                && definition.getRole() == AbstractBeanDefinition.ROLE_APPLICATION) {
            Class<?> type = beanFactory.getType(name);
            @SuppressWarnings("unchecked")
            final Class<Object> cls = (Class<Object>) type;
            final String beanName = name;
            Provider<Object> provider = new BeanFactoryProvider(beanFactory, beanName, type);
            if (!cls.isInterface() && !ClassUtils.isCglibProxyClass(cls)) {
                bindConditionally(binder, name, cls, provider);
            }/* w  ww. j  a  v  a  2s . c o m*/
            for (Class<?> iface : ClassUtils.getAllInterfacesForClass(cls)) {
                @SuppressWarnings("unchecked")
                Class<Object> unchecked = (Class<Object>) iface;
                bindConditionally(binder, name, unchecked, provider);
            }
        }
    }
}

From source file:org.jdal.aop.SerializableProxyUtils.java

public static BeanDefinitionHolder createSerializableProxy(BeanDefinitionHolder definition,
        BeanDefinitionRegistry registry, boolean proxyTargetClass) {

    String originalBeanName = definition.getBeanName();
    BeanDefinition targetDefinition = definition.getBeanDefinition();

    // Create a scoped proxy definition for the original bean name,
    // "hiding" the target bean in an internal target definition.
    RootBeanDefinition proxyDefinition = new RootBeanDefinition(SerializableProxyFactoryBean.class);
    proxyDefinition.setOriginatingBeanDefinition(definition.getBeanDefinition());
    proxyDefinition.setSource(definition.getSource());
    proxyDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

    String targetBeanName = getTargetBeanName(originalBeanName);
    proxyDefinition.getPropertyValues().add("targetBeanName", targetBeanName);

    if (proxyTargetClass) {
        targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
    } else {/* ww w.  j ava  2s .c  o  m*/
        proxyDefinition.getPropertyValues().add("proxyTargetClass", Boolean.FALSE);
    }

    // Copy autowire settings from original bean definition.
    proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
    proxyDefinition.setPrimary(targetDefinition.isPrimary());
    if (targetDefinition instanceof AbstractBeanDefinition) {
        proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
    }

    // Set singleton property of FactoryBean
    proxyDefinition.getPropertyValues().add("singleton", !targetDefinition.isPrototype());

    // The target bean should be ignored in favor of the scoped proxy.
    targetDefinition.setAutowireCandidate(false);
    targetDefinition.setPrimary(false);

    // Register the target bean as separate bean in the factory.
    registry.registerBeanDefinition(targetBeanName, targetDefinition);

    // Return the scoped proxy definition as primary bean definition
    // (potentially an inner bean).
    return new BeanDefinitionHolder(proxyDefinition, originalBeanName, definition.getAliases());
}

From source file:org.constretto.spring.EnvironmentAnnotationConfigurer.java

@SuppressWarnings("unchecked")
private void removeNonAnnotatedBeansFromAutowireForType(Class lookupClass,
        ConfigurableListableBeanFactory configurableListableBeanFactory) throws ClassNotFoundException {
    List<String> beanNames = new ArrayList<String>();
    Class[] interfaces = lookupClass.getInterfaces();
    for (Class anInterface : interfaces) {
        beanNames.addAll(asList(BeanFactoryUtils
                .beanNamesForTypeIncludingAncestors(configurableListableBeanFactory, anInterface)));
    }/*from   w w w .  j a va2  s.c  o m*/
    List<BeanDefinition> potentialMatches = new ArrayList<BeanDefinition>();
    for (String beanName : beanNames) {
        BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition(beanName);
        Class beanClass = Class.forName(beanDefinition.getBeanClassName());
        beanDefinition.setAttribute(INCLUDE_IN_COLLECTIONS, beanClass.getInterfaces());
        Environment environmentAnnotation = findEnvironmentAnnotation(beanClass);
        if (environmentAnnotation == null) {
            beanDefinition.setAutowireCandidate(false);
        } else {
            potentialMatches.add(beanDefinition);
        }
    }
    if (potentialMatches.size() == 1) {
        potentialMatches.get(0).setAutowireCandidate(true);
    } else {
        List<BeanDefinition> highestPriorityBeans = new ArrayList<BeanDefinition>();
        for (BeanDefinition potentialMatch : potentialMatches) {
            if (potentialMatch.isAutowireCandidate()) {
                potentialMatch.setAutowireCandidate(false);
                highestPriorityBeans = prioritizeBeans(potentialMatch, highestPriorityBeans);
            }
        }
        if (highestPriorityBeans.size() == 1) {
            highestPriorityBeans.get(0).setAutowireCandidate(true);
        } else {
            List<String> equalPriorityBeans = new ArrayList<String>();
            for (BeanDefinition highestPriorityBean : highestPriorityBeans) {
                equalPriorityBeans.add(highestPriorityBean.getBeanClassName());
            }
            throw new ConstrettoException("More than one bean with the class or interface + ["
                    + lookupClass.getSimpleName()
                    + "] registered with same tag. Could not resolve priority. To fix this, remove one of the following beans "
                    + equalPriorityBeans.toString());
        }
    }
}

From source file:org.xaloon.wicket.component.inject.spring.CdiProxyFieldValueFactory.java

private final String getBeanNameOfClass(ApplicationContext ctx, Class<?> clazz) {
    // get the list of all possible matching beans
    List<String> names = new ArrayList<String>(
            Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, clazz)));

    // filter out beans that are not candidates for autowiring
    Iterator<String> it = names.iterator();
    while (it.hasNext()) {
        final String possibility = it.next();
        if (ctx instanceof AbstractApplicationContext) {
            BeanDefinition beanDef = getBeanDefinition(((AbstractApplicationContext) ctx).getBeanFactory(),
                    possibility);/*  www.j  a  va  2s  .co  m*/
            if (BeanFactoryUtils.isFactoryDereference(possibility) || possibility.startsWith("scopedTarget.")
                    || !beanDef.isAutowireCandidate()) {
                it.remove();
            }
        }
    }

    if (names.isEmpty()) {
        return null;
    } else if (names.size() > 1) {
        if (ctx instanceof AbstractApplicationContext) {
            List<String> primaries = new ArrayList<String>();
            for (String name : names) {
                BeanDefinition beanDef = getBeanDefinition(((AbstractApplicationContext) ctx).getBeanFactory(),
                        name);
                if (beanDef instanceof AbstractBeanDefinition) {
                    if (((AbstractBeanDefinition) beanDef).isPrimary()) {
                        primaries.add(name);
                    }
                }
            }
            if (primaries.size() == 1) {
                return primaries.get(0);
            }
        }
        StringBuilder msg = new StringBuilder();
        msg.append("More than one bean of type [");
        msg.append(clazz.getName());
        msg.append("] found, you have to specify the name of the bean ");
        msg.append("(@Named(\"foo\")) in order to resolve this conflict. ");
        msg.append("Matched beans: ");
        msg.append(Strings.join(",", names.toArray(new String[0])));
        throw new IllegalStateException(msg.toString());
    } else {
        return names.get(0);
    }
}

From source file:ro.pippo.spring.AnnotationFieldValueProvider.java

private String getBeanNameOfClass(Class<?> clazz) {
    // get the list of all possible matching beans
    List<String> names = Arrays
            .asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, clazz));

    // filter out beans that are not candidates for auto wiring
    if (applicationContext instanceof AbstractApplicationContext) {
        Iterator<String> iterator = names.iterator();
        while (iterator.hasNext()) {
            String possibility = iterator.next();
            BeanDefinition beanDef = getBeanDefinition(
                    ((AbstractApplicationContext) applicationContext).getBeanFactory(), possibility);
            if (BeanFactoryUtils.isFactoryDereference(possibility) || possibility.startsWith("scopedTarget.")
                    || (beanDef != null && !beanDef.isAutowireCandidate())) {
                iterator.remove();/*ww  w .  j  a v  a  2s . c om*/
            }
        }
    }

    if (names.isEmpty()) {
        return null;
    }

    if (names.size() > 1) {
        if (applicationContext instanceof AbstractApplicationContext) {
            List<String> primaries = new ArrayList<>();
            for (String name : names) {
                BeanDefinition beanDef = getBeanDefinition(
                        ((AbstractApplicationContext) applicationContext).getBeanFactory(), name);
                if (beanDef instanceof AbstractBeanDefinition) {
                    if (beanDef.isPrimary()) {
                        primaries.add(name);
                    }
                }
            }
            if (primaries.size() == 1) {
                return primaries.get(0);
            }
        }
        StringBuilder message = new StringBuilder();
        message.append("More than one bean of type [");
        message.append(clazz.getName());
        message.append("] found, you have to specify the name of the bean ");
        message.append("(@Named(\"foo\") if using @javax.inject classes) in order to resolve this conflict. ");
        message.append("Matched beans: ");
        message.append(names);
        throw new PippoRuntimeException(message.toString());
    }

    return names.get(0);
}

From source file:me.springframework.di.spring.SpringConfigurationLoader.java

/**
 * Loads a {@link MutableInstance} from one of the {@link BeanDefinition}s
 * provided by the {@link BeanDefinitionRegistry} passed in.
 * //from www.  j  av  a  2  s . com
 * @param instance
 *            A {@link MutableInstance} to be populated.
 * @param definition
 *            A {@link BeanDefinition}, providing the meta data.
 */
private static void load(MutableInstance instance, BeanDefinition definition, MutableContext context) {
    instance.setReferencedType(definition.getBeanClassName());
    instance.setPrimitive(false);
    instance.setLazyInit(definition.isLazyInit());
    instance.setId("source" + counter++);
    instance.setFactoryMethod(definition.getFactoryMethodName());
    instance.setFactoryInstance(definition.getFactoryBeanName());
    if (ConfigurableBeanFactory.SCOPE_SINGLETON.equals(definition.getScope())) {
        instance.setScope(Scope.SINGLETON);
    }
    if (ConfigurableBeanFactory.SCOPE_PROTOTYPE.equals(definition.getScope())) {
        instance.setScope(Scope.PROTOTYPE);
    }
    if (definition instanceof AbstractBeanDefinition) {
        instance.setInitMethod(((AbstractBeanDefinition) definition).getInitMethodName());
        instance.setDestroyMethod(((AbstractBeanDefinition) definition).getDestroyMethodName());
    }
    if (!definition.getConstructorArgumentValues().isEmpty()) {
        List<MutableConstructorArgument> arguments = new ArrayList<MutableConstructorArgument>();
        for (Object object : definition.getConstructorArgumentValues().getGenericArgumentValues()) {
            MutableConstructorArgument argument = new MutableConstructorArgument(instance);
            argument.setInstance(instance);
            ValueHolder holder = (ValueHolder) object;
            argument.setSource(loadSource(context, argument, holder.getValue()));
            argument.setType(holder.getType());
            arguments.add(argument);
        }
        instance.setConstructorArguments(arguments);
    }
    Set<MutablePropertySetter> setters = new HashSet<MutablePropertySetter>();
    for (Object object : definition.getPropertyValues().getPropertyValueList()) {
        MutablePropertySetter setter = new MutablePropertySetter(instance);
        setter.setInstance(instance);
        PropertyValue value = (PropertyValue) object;
        setter.setName(value.getName());
        setter.setSource(loadSource(context, setter, value.getValue()));
        setters.add(setter);
    }
    instance.setSetters(setters);

    // added by woj
    instance.setAutowireCandidate(definition.isAutowireCandidate());
    if (definition instanceof AbstractBeanDefinition) {
        instance.setAutowireMode(((AbstractBeanDefinition) definition).getResolvedAutowireMode());
    } else {
        instance.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_NO);
    }
}