Example usage for org.springframework.beans.factory BeanFactoryUtils beanNamesForTypeIncludingAncestors

List of usage examples for org.springframework.beans.factory BeanFactoryUtils beanNamesForTypeIncludingAncestors

Introduction

In this page you can find the example usage for org.springframework.beans.factory BeanFactoryUtils beanNamesForTypeIncludingAncestors.

Prototype

public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, Class<?> type,
        boolean includeNonSingletons, boolean allowEagerInit) 

Source Link

Document

Get all bean names for the given type, including those defined in ancestor factories.

Usage

From source file:io.github.hzpz.spring.boot.autoconfigure.mongeez.MongoDbFactoryDependsOnPostProcessor.java

private String[] getMongoDbFactoryBeanNames(ListableBeanFactory beanFactory) {
    return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, MongoDbFactory.class, true, false);
}

From source file:de.itsvs.cwtrpc.controller.AutowiredRemoteServiceGroupConfig.java

public void afterPropertiesSet() {
    final Log log;
    final ListableBeanFactory beanFactory;
    final String[] beanNames;
    final List<RemoteServiceConfig> serviceConfigs;

    log = LogFactory.getLog(AutowiredRemoteServiceGroupConfig.class);
    log.debug("Searching for remote services");

    beanFactory = getApplicationContext();
    beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, RemoteService.class, true,
            false);//from w ww.  ja  va2s.c  om
    if (beanNames.length == 0) {
        return;
    }

    serviceConfigs = new ArrayList<RemoteServiceConfig>();
    for (String beanName : beanNames) {
        final Class<?> beanType;
        final Class<?> serviceInterface;

        beanType = beanFactory.getType(beanName);
        serviceInterface = getRemoteServiceInterface(beanType);
        if (serviceInterface != null) {
            if (serviceInterface.getAnnotation(RemoteServiceRelativePath.class) != null) {
                if (isAcceptedServiceInterface(serviceInterface)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Adding service '" + beanName + "'");
                    }
                    serviceConfigs.add(new RemoteServiceConfig(beanName));
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Ignoring service '" + beanName + "' since service does not specify "
                            + "remote service relative path");
                }
            }
        } else {
            if (log.isInfoEnabled()) {
                log.info("Ignoring service '" + beanName + "' since it implements multiple "
                        + "remote service interfaces");
            }
        }
    }

    setServiceConfigs(serviceConfigs);
}

From source file:org.synyx.hades.domain.auditing.support.AuditingBeanFactoryPostProcessor.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {

    if (!isSpringConfigured(beanFactory)) {
        return;//ww w . j a va2 s  .  c om
    }

    for (String beanName : beanFactory.getBeanDefinitionNames()) {

        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);

        if (CLASSES_TO_DEPEND.contains(definition.getBeanClassName())) {
            definition.setDependsOn(
                    StringUtils.addStringToArray(definition.getDependsOn(), BEAN_CONFIGURER_ASPECT_BEAN_NAME));
        }
    }

    for (String beanName : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, AuditorAware.class,
            true, false)) {
        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
        definition.setLazyInit(true);
    }
}

From source file:org.iterx.miru.support.spring.bean.factory.SpringBeanFactory.java

public Object getBeanOfType(Class type) {
    assert (type != null) : "type == null";

    try {/*  w w w  .  j a v  a2 s  .  c  om*/
        String[] names;

        if ((beanFactory instanceof ListableBeanFactory)
                && (names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                        (ListableBeanFactory) beanFactory, type, true, false)).length > 0) {
            Object object;
            String name;

            object = beanFactory.getBean(name = names[0]);
            if (object instanceof BeanAware)
                ((BeanAware) object).setId(name);
            return object;
        }
    } catch (BeansException e) {
        if (LOGGER.isWarnEnabled())
            LOGGER.warn("Failed to create bean implementation [" + type.toString() + "]", e);
    }

    return (parent != null) ? parent.getBeanOfType(type) : null;
}

From source file:org.iterx.miru.support.spring.bean.factory.SpringBeanFactory.java

public Object getBeanOfType(Class[] types) {
    assert (types != null && types.length > 0) : "types == null";
    try {/*from  ww w  . ja  va  2  s  .co m*/
        String[] names;

        if ((beanFactory instanceof ListableBeanFactory)
                && (names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                        (ListableBeanFactory) beanFactory, types[0], true, false)).length > 0) {

            for (int i = 0; i < names.length; i++) {
                Object object;
                String name;
                int j;

                name = names[i];
                object = beanFactory.getBean(name);

                for (j = types.length; j-- > 1;) {
                    if (!types[j].isAssignableFrom(object.getClass()))
                        break;
                }

                if (j < 1) {
                    if (object instanceof BeanAware)
                        ((BeanAware) object).setId(name);
                    return object;
                }
            }
        }
    } catch (BeansException e) {
        if (LOGGER.isWarnEnabled()) {
            StringBuffer buffer;

            buffer = new StringBuffer();
            for (int i = 0; i < types.length; i++) {
                buffer.append(',');
                buffer.append(types[i]);
            }
            LOGGER.warn("Failed to create bean implementation [" + buffer.substring(1) + "]", e);
        }
    }

    return (parent != null) ? parent.getBeanOfType(types) : null;
}

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

@Override
public void replaceWithConstant(Set<Class<?>> contracts, String name, Object instance) {
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();

    for (Class<?> contract : contracts) {
        String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, contract, true,
                false);/*w  w w. ja  va2 s.c  om*/
        for (String beanName : beanNames) {
            beanFactory.removeBeanDefinition(beanName);
        }
    }

    beanFactory.registerSingleton(name, instance);
}

From source file:org.rosenvold.spring.convention.ConventionBeanFactory.java

private String[] getCandidateNames(Class requiredType, DependencyDescriptor descriptor) {
    String[] strings = typeCache.get(requiredType);
    if (strings != null) {
        return strings;
    }//  ww  w.ja v  a  2s . co m
    strings = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this, requiredType, true,
            descriptor.isEager());
    typeCache.put(requiredType, strings);
    return strings;
}

From source file:org.acegisecurity.taglibs.authz.AclTag.java

public int doStartTag() throws JspException {
    if ((null == hasPermission) || "".equals(hasPermission)) {
        return Tag.SKIP_BODY;
    }/*  w ww . j  av a 2s  .  c o m*/

    final String evaledPermissionsString = ExpressionEvaluationUtils.evaluateString("hasPermission",
            hasPermission, pageContext);

    Integer[] requiredIntegers = null;

    try {
        requiredIntegers = parseIntegersString(evaledPermissionsString);
    } catch (NumberFormatException nfe) {
        throw new JspException(nfe);
    }

    Object resolvedDomainObject = null;

    if (domainObject instanceof String) {
        resolvedDomainObject = ExpressionEvaluationUtils.evaluate("domainObject", (String) domainObject,
                Object.class, pageContext);
    } else {
        resolvedDomainObject = domainObject;
    }

    if (resolvedDomainObject == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("domainObject resolved to null, so including tag body");
        }

        // Of course they have access to a null object!
        return Tag.EVAL_BODY_INCLUDE;
    }

    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "SecurityContextHolder did not return a non-null Authentication object, so skipping tag body");
        }

        return Tag.SKIP_BODY;
    }

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    ApplicationContext context = getContext(pageContext);
    String[] beans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, AclManager.class, false,
            false);

    if (beans.length == 0) {
        throw new JspException("No AclManager would found the application context: " + context.toString());
    }

    AclManager aclManager = (AclManager) context.getBean(beans[0]);

    // Obtain aclEntrys applying to the current Authentication object
    AclEntry[] acls = aclManager.getAcls(resolvedDomainObject, auth);

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication: '" + auth + "' has: " + ((acls == null) ? 0 : acls.length)
                + " AclEntrys for domain object: '" + resolvedDomainObject + "' from AclManager: '"
                + aclManager.toString() + "'");
    }

    if ((acls == null) || (acls.length == 0)) {
        return Tag.SKIP_BODY;
    }

    for (int i = 0; i < acls.length; i++) {
        // Locate processable AclEntrys
        if (acls[i] instanceof BasicAclEntry) {
            BasicAclEntry processableAcl = (BasicAclEntry) acls[i];

            // See if principal has any of the required permissions
            for (int y = 0; y < requiredIntegers.length; y++) {
                if (processableAcl.isPermitted(requiredIntegers[y].intValue())) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Including tag body as found permission: " + requiredIntegers[y]
                                + " due to AclEntry: '" + processableAcl + "'");
                    }

                    return Tag.EVAL_BODY_INCLUDE;
                }
            }
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("No permission, so skipping tag body");
    }

    return Tag.SKIP_BODY;
}

From source file:org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.MandatoryImporterDependencyFactory.java

public Collection<OsgiServiceDependency> getServiceDependencies(BundleContext bundleContext,
        ConfigurableListableBeanFactory beanFactory)
        throws BeansException, InvalidSyntaxException, BundleException {

    boolean trace = log.isTraceEnabled();

    String[] singleBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory,
            OsgiServiceProxyFactoryBean.class, true, false);

    if (trace) {/*from w w  w.  ja v  a 2 s  .  com*/
        log.trace("Discovered single proxy importers " + Arrays.toString(singleBeans));
    }
    String[] collectionBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory,
            OsgiServiceCollectionProxyFactoryBean.class, true, false);

    if (trace) {
        log.trace("Discovered collection proxy importers " + Arrays.toString(collectionBeans));
    }

    String[] beans = StringUtils.concatenateStringArrays(singleBeans, collectionBeans);

    List<OsgiServiceDependency> beansCollections = new ArrayList<OsgiServiceDependency>(beans.length);

    for (int i = 0; i < beans.length; i++) {
        if (!isLazy(beanFactory, beans[i])) {
            String beanName = (beans[i].startsWith(BeanFactory.FACTORY_BEAN_PREFIX) ? beans[i]
                    : BeanFactory.FACTORY_BEAN_PREFIX + beans[i]);

            SmartFactoryBean<?> reference = beanFactory.getBean(beanName, SmartFactoryBean.class);

            OsgiServiceDependency dependency;
            if (reference instanceof OsgiServiceProxyFactoryBean) {
                OsgiServiceProxyFactoryBean importer = (OsgiServiceProxyFactoryBean) reference;

                dependency = new DefaultOsgiServiceDependency(beanName, importer.getUnifiedFilter(),
                        Availability.MANDATORY.equals(importer.getAvailability()));
            } else {
                OsgiServiceCollectionProxyFactoryBean importer = (OsgiServiceCollectionProxyFactoryBean) reference;

                dependency = new DefaultOsgiServiceDependency(beanName, importer.getUnifiedFilter(),
                        Availability.MANDATORY.equals(importer.getAvailability()));
            }

            if (trace)
                log.trace("Eager importer " + beanName + " implies dependecy " + dependency);

            beansCollections.add(dependency);
        } else {
            String name = (beans[i].startsWith(BeanFactory.FACTORY_BEAN_PREFIX) ? beans[i].substring(1)
                    : beans[i]);
            if (beanFactory.containsBeanDefinition(name)) {
                BeanDefinition def = beanFactory.getBeanDefinition(name);
                MutablePropertyValues values = def.getPropertyValues();
                // figure out if it's a mandatory bean
                PropertyValue value = values.getPropertyValue(AVAILABILITY_PROP);
                if (value != null && Availability.MANDATORY.equals(value.getValue())) {
                    String[] intfs = getInterfaces(values.getPropertyValue(INTERFACES_PROP));
                    String beanName = getString(values.getPropertyValue(SERVICE_BEAN_NAME_PROP));
                    String filterProp = getString(values.getPropertyValue(FILTER_PROP));

                    // create filter
                    Filter filter = createFilter(intfs, beanName, filterProp);
                    OsgiServiceDependency dependency;
                    dependency = new DefaultOsgiServiceDependency(name, filter, true);

                    if (trace)
                        log.trace("Lazy importer " + beanName + " implies dependecy " + dependency);

                    beansCollections.add(dependency);
                }
            } else {
                if (trace)
                    log.trace("Bean " + name
                            + " is marked as lazy but does not provide a bean definition; ignoring...");
            }
        }
    }

    return beansCollections;
}

From source file:org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.java

/**
 * Find all eligible Advisor beans in the current bean factory,
 * ignoring FactoryBeans and excluding beans that are currently in creation.
 * @return the list of {@link org.springframework.aop.Advisor} beans
 * @see #isEligibleBean//from   w w w  .j  ava 2  s.c  om
 */
public List<Advisor> findAdvisorBeans() {
    // Determine list of advisor bean names, if not cached already.
    String[] advisorNames = null;
    synchronized (this) {
        advisorNames = this.cachedAdvisorBeanNames;
        if (advisorNames == null) {
            // Do not initialize FactoryBeans here: We need to leave all regular beans
            // uninitialized to let the auto-proxy creator apply to them!
            advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Advisor.class,
                    true, false);
            this.cachedAdvisorBeanNames = advisorNames;
        }
    }
    if (advisorNames.length == 0) {
        return new LinkedList<>();
    }

    List<Advisor> advisors = new LinkedList<>();
    for (String name : advisorNames) {
        if (isEligibleBean(name)) {
            if (this.beanFactory.isCurrentlyInCreation(name)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Skipping currently created advisor '" + name + "'");
                }
            } else {
                try {
                    advisors.add(this.beanFactory.getBean(name, Advisor.class));
                } catch (BeanCreationException ex) {
                    Throwable rootCause = ex.getMostSpecificCause();
                    if (rootCause instanceof BeanCurrentlyInCreationException) {
                        BeanCreationException bce = (BeanCreationException) rootCause;
                        String bceBeanName = bce.getBeanName();
                        if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Skipping advisor '" + name
                                        + "' with dependency on currently created bean: " + ex.getMessage());
                            }
                            // Ignore: indicates a reference back to the bean we're trying to advise.
                            // We want to find advisors other than the currently created bean itself.
                            continue;
                        }
                    }
                    throw ex;
                }
            }
        }
    }
    return advisors;
}