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

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

Introduction

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

Prototype

void registerSingleton(String beanName, Object singletonObject);

Source Link

Document

Register the given existing object as singleton in the bean registry, under the given bean name.

Usage

From source file:org.springframework.boot.context.logging.LoggingApplicationListener.java

private void onApplicationPreparedEvent(ApplicationPreparedEvent event) {
    ConfigurableListableBeanFactory beanFactory = event.getApplicationContext().getBeanFactory();
    if (!beanFactory.containsBean(LOGGING_SYSTEM_BEAN_NAME)) {
        beanFactory.registerSingleton(LOGGING_SYSTEM_BEAN_NAME, this.loggingSystem);
    }//from w  ww.  jav  a  2 s  . co  m
}

From source file:org.springframework.cloud.gcp.data.spanner.test.AbstractSpannerIntegrationTest.java

protected void createDatabaseWithSchema() {
    this.tableNameSuffix = String.valueOf(System.currentTimeMillis());
    ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) this.applicationContext)
            .getBeanFactory();/* w  w  w.j ava  2  s. com*/
    beanFactory.registerSingleton("tableNameSuffix", this.tableNameSuffix);

    List<String> createStatements = createSchemaStatements();

    if (!this.spannerDatabaseAdminTemplate.databaseExists()) {
        LOGGER.debug(this.getClass() + " - Integration database created with schema: " + createStatements);
        this.spannerDatabaseAdminTemplate.executeDdlStrings(createStatements, true);
    } else {
        LOGGER.debug(this.getClass() + " - schema created: " + createStatements);
        this.spannerDatabaseAdminTemplate.executeDdlStrings(createStatements, false);
    }
}

From source file:org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.java

/**
 * Register an error channel for the destination when an async send error is received.
 * Bridge the channel to the global error channel (if present).
 * @param destination the destination./*  w w  w .java 2 s  .co m*/
 * @return the channel.
 */
private SubscribableChannel registerErrorInfrastructure(ProducerDestination destination) {
    ConfigurableListableBeanFactory beanFactory = getApplicationContext().getBeanFactory();
    String errorChannelName = errorsBaseName(destination);
    SubscribableChannel errorChannel = null;
    if (getApplicationContext().containsBean(errorChannelName)) {
        Object errorChannelObject = getApplicationContext().getBean(errorChannelName);
        if (!(errorChannelObject instanceof SubscribableChannel)) {
            throw new IllegalStateException(
                    "Error channel '" + errorChannelName + "' must be a SubscribableChannel");
        }
        errorChannel = (SubscribableChannel) errorChannelObject;
    } else {
        errorChannel = new PublishSubscribeChannel();
        beanFactory.registerSingleton(errorChannelName, errorChannel);
        errorChannel = (PublishSubscribeChannel) beanFactory.initializeBean(errorChannel, errorChannelName);
    }
    MessageChannel defaultErrorChannel = null;
    if (getApplicationContext().containsBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)) {
        defaultErrorChannel = getApplicationContext().getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME,
                MessageChannel.class);
    }
    if (defaultErrorChannel != null) {
        BridgeHandler errorBridge = new BridgeHandler();
        errorBridge.setOutputChannel(defaultErrorChannel);
        errorChannel.subscribe(errorBridge);
        String errorBridgeHandlerName = getErrorBridgeName(destination);
        beanFactory.registerSingleton(errorBridgeHandlerName, errorBridge);
        beanFactory.initializeBean(errorBridge, errorBridgeHandlerName);
    }
    return errorChannel;
}

From source file:org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.java

/**
 * Build an errorChannelRecoverer that writes to a pub/sub channel for the destination
 * when an exception is thrown to a consumer.
 * @param destination the destination.// www  . j  a va 2  s.c om
 * @param group the group.
 * @param consumerProperties the properties.
 * @param true if this is for a polled consumer.
 * @return the ErrorInfrastructure which is a holder for the error channel, the recoverer and the
 * message handler that is subscribed to the channel.
 */
protected final ErrorInfrastructure registerErrorInfrastructure(ConsumerDestination destination, String group,
        C consumerProperties, boolean polled) {

    ErrorMessageStrategy errorMessageStrategy = getErrorMessageStrategy();
    ConfigurableListableBeanFactory beanFactory = getApplicationContext().getBeanFactory();
    String errorChannelName = errorsBaseName(destination, group, consumerProperties);
    SubscribableChannel errorChannel = null;
    if (getApplicationContext().containsBean(errorChannelName)) {
        Object errorChannelObject = getApplicationContext().getBean(errorChannelName);
        if (!(errorChannelObject instanceof SubscribableChannel)) {
            throw new IllegalStateException(
                    "Error channel '" + errorChannelName + "' must be a SubscribableChannel");
        }
        errorChannel = (SubscribableChannel) errorChannelObject;
    } else {
        errorChannel = new BinderErrorChannel();
        beanFactory.registerSingleton(errorChannelName, errorChannel);
        errorChannel = (LastSubscriberAwareChannel) beanFactory.initializeBean(errorChannel, errorChannelName);
    }
    ErrorMessageSendingRecoverer recoverer;
    if (errorMessageStrategy == null) {
        recoverer = new ErrorMessageSendingRecoverer(errorChannel);
    } else {
        recoverer = new ErrorMessageSendingRecoverer(errorChannel, errorMessageStrategy);
    }
    String recovererBeanName = getErrorRecovererName(destination, group, consumerProperties);
    beanFactory.registerSingleton(recovererBeanName, recoverer);
    beanFactory.initializeBean(recoverer, recovererBeanName);
    MessageHandler handler;
    if (polled) {
        handler = getPolledConsumerErrorMessageHandler(destination, group, consumerProperties);
    } else {
        handler = getErrorMessageHandler(destination, group, consumerProperties);
    }
    MessageChannel defaultErrorChannel = null;
    if (getApplicationContext().containsBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)) {
        defaultErrorChannel = getApplicationContext().getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME,
                MessageChannel.class);
    }
    if (handler == null && errorChannel instanceof LastSubscriberAwareChannel) {
        handler = getDefaultErrorMessageHandler((LastSubscriberAwareChannel) errorChannel,
                defaultErrorChannel != null);
    }
    String errorMessageHandlerName = getErrorMessageHandlerName(destination, group, consumerProperties);
    if (handler != null) {
        beanFactory.registerSingleton(errorMessageHandlerName, handler);
        beanFactory.initializeBean(handler, errorMessageHandlerName);
        errorChannel.subscribe(handler);
    }
    if (defaultErrorChannel != null) {
        BridgeHandler errorBridge = new BridgeHandler();
        errorBridge.setOutputChannel(defaultErrorChannel);
        errorChannel.subscribe(errorBridge);
        String errorBridgeHandlerName = getErrorBridgeName(destination, group, consumerProperties);
        beanFactory.registerSingleton(errorBridgeHandlerName, errorBridge);
        beanFactory.initializeBean(errorBridge, errorBridgeHandlerName);
    }
    return new ErrorInfrastructure(errorChannel, recoverer, handler);
}

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 w  w w .  jav  a 2 s  .c  om
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 w  w.j a  v  a2  s . c o m
 * 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
 *//*from w w  w . j  a  v a2s .c o m*/
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 .  j a  v  a 2s  .  com
 * 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 + "]");
        }
    }
}

From source file:org.springframework.data.gemfire.client.GemfireDataSourcePostProcessor.java

private void createClientRegions(ConfigurableListableBeanFactory beanFactory) {
    GemfireFunctionOperations functionTemplate = new GemfireOnServersFunctionTemplate(cache);

    Iterable<String> regionNames = functionTemplate.executeAndExtract(new ListRegionsOnServerFunction());

    ClientRegionFactory<?, ?> clientRegionFactory = null;

    if (regionNames != null && regionNames.iterator().hasNext()) {
        clientRegionFactory = cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
    }/*w  w w  .  java2  s  . co m*/

    for (String regionName : regionNames) {
        boolean createRegion = true;

        if (beanFactory.containsBean(regionName)) {
            Object existingBean = beanFactory.getBean(regionName);
            Assert.isTrue(existingBean instanceof Region, String.format(
                    "Cannot create a ClientRegion bean named '%1$s'. A bean with this name of type '%2$s' already exists.",
                    regionName, existingBean.getClass().getName()));
            createRegion = false;
        }

        if (createRegion) {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Creating Client Region bean with name '%s'...", regionName));
            }
            beanFactory.registerSingleton(regionName, clientRegionFactory.create(regionName));
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("A Region named '%s' is already defined.", regionName));
            }
        }
    }
}

From source file:org.springframework.integration.configuration.EnableIntegrationTests.java

@Test
public void testSourcePollingChannelAdapterOutputChannelLateBinding() {
    QueueChannel testChannel = new QueueChannel();
    ConfigurableListableBeanFactory beanFactory = (ConfigurableListableBeanFactory) this.context
            .getAutowireCapableBeanFactory();
    beanFactory.registerSingleton("lateBindingChannel", testChannel);
    beanFactory.initializeBean(testChannel, "lateBindingChannel");

    this.autoCreatedChannelMessageSourceAdapter.start();
    Message<?> receive = testChannel.receive(10000);
    assertNotNull(receive);/*from www .  jav a  2 s . c  o  m*/
    assertEquals("bar", receive.getPayload());
    this.autoCreatedChannelMessageSourceAdapter.stop();
}