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

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

Introduction

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

Prototype

public static <T> Map<String, T> beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type,
        boolean includeNonSingletons, boolean allowEagerInit) throws BeansException 

Source Link

Document

Return all beans of the given type or subtypes, also picking up beans defined in ancestor bean factories if the current bean factory is a HierarchicalBeanFactory.

Usage

From source file:org.terasoluna.gfw.web.codelist.CodeListInterceptor.java

/**
 * Extracts the {@code CodeList}s which are to be set to the attribute of {@link HttpServletRequest}
 * <p>/*from   www . jav  a  2s. c o  m*/
 * Among the Beans which implement {@code CodeList} interface, extract the Codelist IDs(Bean IDs) which match<br>
 * with the regular expression specified in {@link #codeListIdPattern}.
 * </p>
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 */
@Override
public void afterPropertiesSet() {

    Assert.notNull(applicationContext, "applicationContext is null.");

    if (codeListIdPattern == null) {
        this.codeListIdPattern = Pattern.compile(".+");
    }

    Map<String, CodeList> definedCodeLists = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
            CodeList.class, false, false);
    Map<String, CodeList> targetCodeLists = new HashMap<String, CodeList>();
    for (CodeList codeList : definedCodeLists.values()) {
        String codeListId = codeList.getCodeListId();
        if (codeListId != null) {
            Matcher codeListIdMatcher = codeListIdPattern.matcher(codeListId);
            if (codeListIdMatcher.matches()) {
                targetCodeLists.put(codeListId, codeList);
            }
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("registered codeList : {}", targetCodeLists.keySet());
    }

    this.codeLists = Collections.unmodifiableCollection(targetCodeLists.values());

}

From source file:org.kmnet.com.fw.web.codelist.CodeListInterceptor.java

/**
 * Extracts the {@code CodeList}s which are to be set to the attribute of {@link HttpServletRequest}
 * <p>/*from  ww  w.ja  va2  s  . c  o m*/
 * Among the Beans which implement {@code CodeList} interface, extract the Codelist IDs(Bean IDs) which match<br>
 * with the regular expression specified in {@link #codeListIdPattern}.
 * </p>
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 */
@Override
public void afterPropertiesSet() {

    Assert.notNull(applicationContext, "applicationContext is null.");

    if (codeListIdPattern == null) {
        this.codeListIdPattern = Pattern.compile(".+");
    }

    Map<String, CodeList> definedCodeLists = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
            CodeList.class, false, false);
    Map<String, CodeList> targetCodeLists = new HashMap<String, CodeList>();
    for (CodeList codeList : definedCodeLists.values()) {
        String codeListId = codeList.getCodeListId();
        Matcher codeListIdMatcher = codeListIdPattern.matcher(codeListId);
        if (codeListIdMatcher.matches()) {
            targetCodeLists.put(codeListId, codeList);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("registered codeList : {}", targetCodeLists.keySet());
    }

    this.codeLists = Collections.unmodifiableCollection(targetCodeLists.values());

}

From source file:biz.deinum.multitenant.aop.target.ContextSwappableTargetSource.java

@SuppressWarnings("unchecked")
private void initTargetRegistries() {
    if (this.registries.isEmpty()) {
        final Map<String, ? extends TargetRegistry> matchingBeans = BeanFactoryUtils
                .beansOfTypeIncludingAncestors(this.context, TargetRegistry.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.registries.addAll((Collection<? extends TargetRegistry<?>>) matchingBeans.values());
            Collections.sort(this.registries, new OrderComparator());
        } else {// w w w  .j a  v  a 2  s.c om
            @SuppressWarnings("rawtypes")
            final BeanFactoryTargetRegistry<?> registry = new BeanFactoryTargetRegistry();
            registry.setBeanFactory(this.context);
            this.registries.add(registry);
        }
    }
}

From source file:com.fengduo.bee.commons.velocity.CustomVelocityLayoutView.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void initViewTools() {
    viewTools = new HashMap<String, Object>();
    Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
            ViewToolsFactory.class, true, false);
    Collection<ViewToolsFactory> values = matchingBeans.values();
    for (ViewToolsFactory factory : values) {
        Map<String, Object> vt = factory.getViewTools();
        if (vt != null) {
            viewTools.putAll(vt);/*from w ww  .  j a va  2 s  .co  m*/
        }
    }
}

From source file:com.mystudy.source.spring.mvc.DispatcherServlet.java

/**
 * Initialize the HandlerMappings used by this class.
 * <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,
 * we default to BeanNameUrlHandlerMapping.
 *//*from  w ww .  ja v a 2  s .  c om*/
private void initHandlerMappings(ApplicationContext context) {
    this.handlerMappings = null;

    if (this.detectAllHandlerMappings) {
        // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
                HandlerMapping.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
            // We keep HandlerMappings in sorted order.
            OrderComparator.sort(this.handlerMappings);
        }
    } else {
        try {
            HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
            this.handlerMappings = Collections.singletonList(hm);
        } catch (NoSuchBeanDefinitionException ex) {
            // Ignore, we'll add a default HandlerMapping later.
        }
    }

    // Ensure we have at least one HandlerMapping, by registering
    // a default HandlerMapping if no other mappings are found.
    if (this.handlerMappings == null) {
        this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
        }
    }
}

From source file:com.mystudy.source.spring.mvc.DispatcherServlet.java

/**
 * Initialize the HandlerAdapters used by this class.
 * <p>If no HandlerAdapter beans are defined in the BeanFactory for this namespace,
 * we default to SimpleControllerHandlerAdapter.
 *//* www.ja  v a  2s.  c om*/
private void initHandlerAdapters(ApplicationContext context) {
    this.handlerAdapters = null;

    if (this.detectAllHandlerAdapters) {
        // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerAdapter> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
                HandlerAdapter.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());
            // We keep HandlerAdapters in sorted order.
            OrderComparator.sort(this.handlerAdapters);
        }
    } else {
        try {
            HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
            this.handlerAdapters = Collections.singletonList(ha);
        } catch (NoSuchBeanDefinitionException ex) {
            // Ignore, we'll add a default HandlerAdapter later.
        }
    }

    // Ensure we have at least some HandlerAdapters, by registering
    // default HandlerAdapters if no other adapters are found.
    if (this.handlerAdapters == null) {
        this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No HandlerAdapters found in servlet '" + getServletName() + "': using default");
        }
    }
}

From source file:com.mystudy.source.spring.mvc.DispatcherServlet.java

/**
 * Initialize the HandlerExceptionResolver used by this class.
 * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
 * we default to no exception resolver.// w  ww.  j av  a2 s .  c  o  m
 */
private void initHandlerExceptionResolvers(ApplicationContext context) {
    this.handlerExceptionResolvers = null;

    if (this.detectAllHandlerExceptionResolvers) {
        // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils
                .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
            // We keep HandlerExceptionResolvers in sorted order.
            OrderComparator.sort(this.handlerExceptionResolvers);
        }
    } else {
        try {
            HandlerExceptionResolver her = context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME,
                    HandlerExceptionResolver.class);
            this.handlerExceptionResolvers = Collections.singletonList(her);
        } catch (NoSuchBeanDefinitionException ex) {
            // Ignore, no HandlerExceptionResolver is fine too.
        }
    }

    // Ensure we have at least some HandlerExceptionResolvers, by registering
    // default HandlerExceptionResolvers if no other resolvers are found.
    if (this.handlerExceptionResolvers == null) {
        this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "No HandlerExceptionResolvers found in servlet '" + getServletName() + "': using default");
        }
    }
}

From source file:com.mystudy.source.spring.mvc.DispatcherServlet.java

/**
 * Initialize the ViewResolvers used by this class.
 * <p>If no ViewResolver beans are defined in the BeanFactory for this
 * namespace, we default to InternalResourceViewResolver.
 *///from  w  w w .ja v a 2s. c o m
private void initViewResolvers(ApplicationContext context) {
    this.viewResolvers = null;

    if (this.detectAllViewResolvers) {
        // Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
        Map<String, ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
                ViewResolver.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.values());
            // We keep ViewResolvers in sorted order.
            OrderComparator.sort(this.viewResolvers);
        }
    } else {
        try {
            ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
            this.viewResolvers = Collections.singletonList(vr);
        } catch (NoSuchBeanDefinitionException ex) {
            // Ignore, we'll add a default ViewResolver later.
        }
    }

    // Ensure we have at least one ViewResolver, by registering
    // a default ViewResolver if no other resolvers are found.
    if (this.viewResolvers == null) {
        this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No ViewResolvers found in servlet '" + getServletName() + "': using default");
        }
    }
}

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

private void doFindDependencies() throws Exception {
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    boolean debug = log.isDebugEnabled();
    boolean trace = log.isTraceEnabled();

    if (trace)//from   ww w  .j a  va 2  s  . c  om
        log.trace("Looking for dependency factories inside bean factory [" + beanFactory.toString() + "]");

    Map<String, OsgiServiceDependencyFactory> localFactories = BeanFactoryUtils
            .beansOfTypeIncludingAncestors(beanFactory, OsgiServiceDependencyFactory.class, true, false);

    if (trace)
        log.trace("Discovered local dependency factories: " + localFactories.keySet());

    dependencyFactories.addAll(localFactories.values());

    for (Iterator<OsgiServiceDependencyFactory> iterator = dependencyFactories.iterator(); iterator
            .hasNext();) {
        OsgiServiceDependencyFactory dependencyFactory = iterator.next();
        Collection<OsgiServiceDependency> discoveredDependencies = null;

        if (trace) {
            log.trace("Interogating dependency factory " + dependencyFactory);
        }
        try {
            discoveredDependencies = dependencyFactory.getServiceDependencies(bundleContext, beanFactory);
        } catch (Exception ex) {
            log.warn("Dependency factory " + dependencyFactory
                    + " threw exception while detecting dependencies for beanFactory " + beanFactory + " in "
                    + context.getDisplayName(), ex);
            throw ex;
        }
        // add the dependencies one by one
        if (discoveredDependencies != null)
            for (OsgiServiceDependency dependency : discoveredDependencies) {
                if (dependency.isMandatory()) {
                    MandatoryServiceDependency msd = new MandatoryServiceDependency(bundleContext, dependency);
                    synchronized (monitor) {
                        dependencies.put(msd, dependency.getBeanName());
                    }

                    if (!msd.isServicePresent()) {
                        log.info("Adding OSGi service dependency for importer [" + msd.getBeanName()
                                + "] matching OSGi filter [" + msd.filterAsString + "]");
                        synchronized (monitor) {
                            unsatisfiedDependencies.put(msd, dependency.getBeanName());
                        }
                    } else {
                        if (debug)
                            log.debug("OSGi service dependency for importer [" + msd.getBeanName()
                                    + "] is already satisfied");
                    }
                }
            }
    }
}

From source file:org.kuali.rice.krad.data.jpa.JpaPersistenceProvider.java

/**
 * Gets any {@link PersistenceExceptionTranslator}s from the {@link BeanFactory}.
 *
 * @param beanFactory The {@link BeanFactory} to use.
 *
 * @return A {@link PersistenceExceptionTranslator} from the {@link BeanFactory}.
 *//*w  w  w. j a  va2 s  .  c  o  m*/
protected PersistenceExceptionTranslator detectPersistenceExceptionTranslators(
        ListableBeanFactory beanFactory) {
    // Find all translators, being careful not to activate FactoryBeans.
    Map<String, PersistenceExceptionTranslator> pets = BeanFactoryUtils
            .beansOfTypeIncludingAncestors(beanFactory, PersistenceExceptionTranslator.class, false, false);
    ChainedPersistenceExceptionTranslator cpet = new ChainedPersistenceExceptionTranslator();
    for (PersistenceExceptionTranslator pet : pets.values()) {
        cpet.addDelegate(pet);
    }
    // always add one last persistence exception translator as a catch all
    cpet.addDelegate(new DefaultPersistenceExceptionTranslator());
    return cpet;
}