Example usage for org.springframework.beans.factory.config ConfigurableListableBeanFactory containsLocalBean

List of usage examples for org.springframework.beans.factory.config ConfigurableListableBeanFactory containsLocalBean

Introduction

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

Prototype

boolean containsLocalBean(String name);

Source Link

Document

Return whether the local bean factory contains a bean of the given name, ignoring beans defined in ancestor contexts.

Usage

From source file:org.archive.spring.PathSharingContext.java

/**
 * Initialize the LifecycleProcessor./*w  ww  .  j  a  v a  2 s. c o m*/
 * Uses HeritrixLifecycleProcessor, which prevents an automatic lifecycle
 * start(), if none defined in the context.
 * @see org.springframework.context.support.DefaultLifecycleProcessor
 */
protected void initLifecycleProcessor() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (!beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
        HeritrixLifecycleProcessor obj = (HeritrixLifecycleProcessor) beanFactory
                .createBean(HeritrixLifecycleProcessor.class);
        beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, obj);
    }
    super.initLifecycleProcessor();
}

From source file:com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceExporter.java

/**
 * Find a {@link BeanDefinition} in the {@link BeanFactory} or it's parents.
 *///from w ww  . j  a  va  2s . c  o  m
private BeanDefinition findBeanDefintion(ConfigurableListableBeanFactory beanFactory, String serviceBeanName) {
    if (beanFactory.containsLocalBean(serviceBeanName)) {
        return beanFactory.getBeanDefinition(serviceBeanName);
    }
    BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory();
    if (parentBeanFactory != null && ConfigurableListableBeanFactory.class.isInstance(parentBeanFactory)) {
        return findBeanDefintion((ConfigurableListableBeanFactory) parentBeanFactory, serviceBeanName);
    }
    throw new RuntimeException(format("Bean with name '%s' can no longer be found.", serviceBeanName));
}

From source file:lodsve.core.condition.OnBeanCondition.java

private boolean containsBean(ConfigurableListableBeanFactory beanFactory, String beanName,
        boolean considerHierarchy) {
    if (considerHierarchy) {
        return beanFactory.containsBean(beanName);
    }//from w ww  .j  a  va 2  s .c  o  m
    return beanFactory.containsLocalBean(beanName);
}

From source file:lodsve.core.condition.OnBeanCondition.java

private String[] getBeanNamesForAnnotation(ConfigurableListableBeanFactory beanFactory, String type,
        ClassLoader classLoader, boolean considerHierarchy) throws LinkageError {
    String[] result = NO_BEANS;//  w  w  w . j  av  a 2 s.c o  m
    try {
        @SuppressWarnings("unchecked")
        Class<? extends Annotation> typeClass = (Class<? extends Annotation>) ClassUtils.forName(type,
                classLoader);
        result = beanFactory.getBeanNamesForAnnotation(typeClass);
        if (considerHierarchy) {
            if (beanFactory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
                String[] parentResult = getBeanNamesForAnnotation(
                        (ConfigurableListableBeanFactory) beanFactory.getParentBeanFactory(), type, classLoader,
                        true);
                List<String> resultList = new ArrayList<String>();
                resultList.addAll(Arrays.asList(result));
                for (String beanName : parentResult) {
                    if (!resultList.contains(beanName) && !beanFactory.containsLocalBean(beanName)) {
                        resultList.add(beanName);
                    }
                }
                result = StringUtils.toStringArray(resultList);
            }
        }
        return result;
    } catch (ClassNotFoundException ex) {
        return NO_BEANS;
    }
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.activator.BlueprintContainerProcessor.java

public void preProcessRefresh(final ConfigurableOsgiBundleApplicationContext context) {
    final BundleContext bundleContext = context.getBundleContext();
    // create the ModuleContext adapter
    final BlueprintContainer blueprintContainer = createBlueprintContainer(context);

    // 1. add event listeners
    // add service publisher
    context.addApplicationListener(new BlueprintContainerServicePublisher(blueprintContainer, bundleContext));
    // add waiting event broadcaster
    context.addApplicationListener(new BlueprintWaitingEventDispatcher(context.getBundleContext()));

    // 2. add environmental managers
    context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {

        private static final String BLUEPRINT_BUNDLE = "blueprintBundle";
        private static final String BLUEPRINT_BUNDLE_CONTEXT = "blueprintBundleContext";
        private static final String BLUEPRINT_CONTAINER = "blueprintContainer";
        private static final String BLUEPRINT_EXTENDER = "blueprintExtenderBundle";
        private static final String BLUEPRINT_CONVERTER = "blueprintConverter";

        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            // lazy logger evaluation
            Log logger = LogFactory.getLog(context.getClass());

            if (!(beanFactory instanceof BeanDefinitionRegistry)) {
                logger.warn("Environmental beans will be registered as singletons instead "
                        + "of usual bean definitions since beanFactory " + beanFactory
                        + " is not a BeanDefinitionRegistry");
            }/*from  w ww  .j  a v  a 2 s.co  m*/

            // add blueprint container bean
            addPredefinedBlueprintBean(beanFactory, BLUEPRINT_BUNDLE, bundleContext.getBundle(), logger);
            addPredefinedBlueprintBean(beanFactory, BLUEPRINT_BUNDLE_CONTEXT, bundleContext, logger);
            addPredefinedBlueprintBean(beanFactory, BLUEPRINT_CONTAINER, blueprintContainer, logger);
            // addPredefinedBlueprintBean(beanFactory, BLUEPRINT_EXTENDER, extenderBundle, logger);
            addPredefinedBlueprintBean(beanFactory, BLUEPRINT_CONVERTER,
                    new SpringBlueprintConverter(beanFactory), logger);

            // add Blueprint conversion service
            // String[] beans = beanFactory.getBeanNamesForType(BlueprintConverterConfigurer.class, false, false);
            // if (ObjectUtils.isEmpty(beans)) {
            // beanFactory.addPropertyEditorRegistrar(new BlueprintEditorRegistrar());
            // }
            beanFactory.setConversionService(
                    new SpringBlueprintConverterService(beanFactory.getConversionService(), beanFactory));
        }

        private void addPredefinedBlueprintBean(ConfigurableListableBeanFactory beanFactory, String beanName,
                Object value, Log logger) {
            if (!beanFactory.containsLocalBean(beanName)) {
                logger.debug("Registering pre-defined bean named " + beanName);
                if (beanFactory instanceof BeanDefinitionRegistry) {
                    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

                    GenericBeanDefinition def = new GenericBeanDefinition();
                    def.setBeanClass(ENV_FB_CLASS);
                    ConstructorArgumentValues cav = new ConstructorArgumentValues();
                    cav.addIndexedArgumentValue(0, value);
                    def.setConstructorArgumentValues(cav);
                    def.setLazyInit(false);
                    def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
                    registry.registerBeanDefinition(beanName, def);

                } else {
                    beanFactory.registerSingleton(beanName, value);
                }

            } else {
                logger.warn("A bean named " + beanName
                        + " already exists; aborting registration of the predefined value...");
            }
        }
    });

    // 3. add cycle breaker
    context.addBeanFactoryPostProcessor(cycleBreaker);

    BlueprintEvent creatingEvent = new BlueprintEvent(BlueprintEvent.CREATING, context.getBundle(),
            extenderBundle);
    listenerManager.blueprintEvent(creatingEvent);
    dispatcher.beforeRefresh(creatingEvent);
}

From source file:org.springframework.boot.autoconfigure.condition.AbstractOnBeanCondition.java

protected boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata, List<String> beanClasses,
        List<String> beanNames) throws LinkageError {

    String checking = ConditionLogUtils.getPrefix(this.logger, metadata);

    SearchStrategy search = (SearchStrategy) metadata.getAnnotationAttributes(annotationClass().getName())
            .get("search");
    search = search == null ? SearchStrategy.ALL : search;

    boolean considerHierarchy = search == SearchStrategy.ALL;
    boolean parentOnly = search == SearchStrategy.PARENTS;

    List<String> beanClassesFound = new ArrayList<String>();
    List<String> beanNamesFound = new ArrayList<String>();

    // eagerInit set to false to prevent early instantiation (some
    // factory beans will not be able to determine their object type at this
    // stage, so those are not eligible for matching this condition)
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    if (parentOnly) {
        BeanFactory parent = beanFactory.getParentBeanFactory();
        if (!(parent instanceof ConfigurableListableBeanFactory)) {
            throw new IllegalStateException(
                    "Cannot use parentOnly if parent is not ConfigurableListableBeanFactory");
        }/*from ww  w.  j a  va  2s  .c om*/
        beanFactory = (ConfigurableListableBeanFactory) parent;
    }
    for (String beanClass : beanClasses) {
        try {
            Class<?> type = ClassUtils.forName(beanClass, context.getClassLoader());
            String[] beans = (considerHierarchy
                    ? BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, type, false, false)
                    : beanFactory.getBeanNamesForType(type, false, false));
            if (beans.length != 0) {
                beanClassesFound.add(beanClass);
            }
        } catch (ClassNotFoundException ex) {
            // swallow exception and continue
        }
    }
    for (String beanName : beanNames) {
        if (considerHierarchy ? beanFactory.containsBean(beanName) : beanFactory.containsLocalBean(beanName)) {
            beanNamesFound.add(beanName);
        }
    }

    boolean result = evaluate(beanClassesFound, beanNamesFound);
    if (this.logger.isDebugEnabled()) {
        logFoundResults(checking, "class", beanClasses, beanClassesFound);
        logFoundResults(checking, "name", beanNames, beanClassesFound);
        this.logger.debug(checking + "Match result is: " + result);
    }
    return result;
}

From source file:org.springframework.context.support.AbstractApplicationContext.java

/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 *///from ww w  .j av  a2 s. co  m
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // Tell the internal bean factory to use the context's class loader etc.
    beanFactory.setBeanClassLoader(getClassLoader());
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    // Configure the bean factory with context callbacks.
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

    // BeanFactory interface not registered as resolvable type in a plain factory.
    // MessageSource registered (and found for autowiring) as a bean.
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    // Register early post-processor for detecting inner beans as ApplicationListeners.
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // Detect a LoadTimeWeaver and prepare for weaving, if found.
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        // Set a temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }

    // Register default environment beans.
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
}

From source file:org.springframework.context.support.AbstractApplicationContext.java

/**
 * Initialize the MessageSource.//from  w ww .j  av a2 s  .c  om
 * Use parent's if none defined in this context.
 */
protected void initMessageSource() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
        this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
        // Make MessageSource aware of parent MessageSource.
        if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
            HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
            if (hms.getParentMessageSource() == null) {
                // Only set parent context as parent MessageSource if no parent MessageSource
                // registered already.
                hms.setParentMessageSource(getInternalParentMessageSource());
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using MessageSource [" + this.messageSource + "]");
        }
    } else {
        // Use empty MessageSource to be able to accept getMessage calls.
        DelegatingMessageSource dms = new DelegatingMessageSource();
        dms.setParentMessageSource(getInternalParentMessageSource());
        this.messageSource = dms;
        beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME
                    + "': using default [" + this.messageSource + "]");
        }
    }
}

From source file:org.springframework.context.support.AbstractApplicationContext.java

/**
 * Initialize the ApplicationEventMulticaster.
 * Uses SimpleApplicationEventMulticaster if none defined in the context.
 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
 */// w ww.ja  va2  s.  com
protected void initApplicationEventMulticaster() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
                ApplicationEventMulticaster.class);
        if (logger.isDebugEnabled()) {
            logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    } else {
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
                this.applicationEventMulticaster);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate ApplicationEventMulticaster with name '"
                    + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "': using default ["
                    + this.applicationEventMulticaster + "]");
        }
    }
}

From source file:org.springframework.context.support.AbstractApplicationContext.java

/**
 * Initialize the LifecycleProcessor.//w w w  . ja  v  a 2  s  . c o  m
 * Uses DefaultLifecycleProcessor if none defined in the context.
 * @see org.springframework.context.support.DefaultLifecycleProcessor
 */
protected void initLifecycleProcessor() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
        this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
        if (logger.isDebugEnabled()) {
            logger.debug("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
        }
    } else {
        DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
        defaultProcessor.setBeanFactory(beanFactory);
        this.lifecycleProcessor = defaultProcessor;
        beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate LifecycleProcessor with name '" + LIFECYCLE_PROCESSOR_BEAN_NAME
                    + "': using default [" + this.lifecycleProcessor + "]");
        }
    }
}