Example usage for org.springframework.context ConfigurableApplicationContext getBeanFactory

List of usage examples for org.springframework.context ConfigurableApplicationContext getBeanFactory

Introduction

In this page you can find the example usage for org.springframework.context ConfigurableApplicationContext getBeanFactory.

Prototype

ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

Source Link

Document

Return the internal bean factory of this application context.

Usage

From source file:ru.anr.cmdline.base.BootstrapImpl.java

/**
 * Registration of beans./*ww  w.ja v  a  2  s .  c om*/
 * 
 * @param ctx
 *            A spring context
 * @param clazz
 *            A bean class
 * @param name
 *            A name for bean
 */
protected void createAndRegisterBeanDefinition(ConfigurableApplicationContext ctx, Class<?> clazz,
        String name) {

    RootBeanDefinition rbd = new RootBeanDefinition();
    rbd.setBeanClass(clazz);
    DefaultListableBeanFactory bf = (DefaultListableBeanFactory) ctx.getBeanFactory();
    if (name == null) {
        bf.registerBeanDefinition(clazz.getSimpleName(), rbd);
    } else {
        bf.registerBeanDefinition(name, rbd);
    }
}

From source file:org.springmodules.validation.valang.parser.DefaultVisitor.java

private Function lifeCycleCallbacks(Function function, int line, int column) {
    if (function instanceof BeanFactoryAware) {
        ((BeanFactoryAware) function).setBeanFactory(beanFactory);
    }/*from   w  w w  .j a  va  2s .  co  m*/
    if (function instanceof ApplicationContextAware) {
        ((ApplicationContextAware) function).setApplicationContext(applicationContext);
    }
    if (function instanceof ResourceLoaderAware) {
        ((ResourceLoaderAware) function).setResourceLoader(resourceLoader);
    }
    if (function instanceof MessageSourceAware) {
        ((MessageSourceAware) function).setMessageSource(messageSource);
    }
    if (function instanceof ApplicationEventPublisherAware) {
        ((ApplicationEventPublisherAware) function).setApplicationEventPublisher(applicationEventPublisher);
    }
    if (function instanceof ServletContextAware) {
        ((ServletContextAware) function).setServletContext(servletContext);
    }
    if (function instanceof AbstractFunction) {
        AbstractFunction abstractFunction = (AbstractFunction) function;
        AutowireCapableBeanFactory autowireCapableBeanFactory = null;

        if (abstractFunction.isAutowireByName() || abstractFunction.isAutowireByType()) {
            if (applicationContext instanceof ConfigurableApplicationContext) {
                ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
                autowireCapableBeanFactory = configurableApplicationContext.getBeanFactory();
            } else if (beanFactory instanceof AutowireCapableBeanFactory) {
                autowireCapableBeanFactory = (AutowireCapableBeanFactory) beanFactory;
            } else if (applicationContext == null && beanFactory == null) {
                throw new ValangException(
                        "Could not autowire function: no application context or bean factory available", line,
                        column);
            } else {
                throw new ValangException(
                        "Could not autowire function: application context or bean factory does not support autowiring",
                        line, column);
            }
        }
        if (abstractFunction.isAutowireByName()) {
            autowireCapableBeanFactory.autowireBeanProperties(function,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
        }
        if (abstractFunction.isAutowireByType()) {
            autowireCapableBeanFactory.autowireBeanProperties(function,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
        }
        try {
            abstractFunction.init();
        } catch (Exception e) {
            throw new ValangException("Error initializing function", e, line, column);
        }
    }
    return function;
}

From source file:au.com.permeance.liferay.spring.BeanLocatorDefinitionCopier.java

/**
 * Initialises the supplied application context based on the {@link BeanLocator} associated with this instance by
 * iterating the liferay registered beans (via {@link BeanLocator#getNames()}).
 *
 * @param context the {@link ConfigurableApplicationContext} in which beans should be registered (by calling
 *                {@link ConfigurableApplicationContext#getBeanFactory()}).
 */// w w w.j  a  v a  2 s.  c o m
@Override
protected final void initApplicationContext(final ApplicationContext context) {
    LOG.info(format("Copying bean definitions from %s to %s", beanLocator, context));

    final ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) context;
    @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
    final SingletonBeanRegistry singletonBeanRegistry = configurableApplicationContext.getBeanFactory();

    final String[] names = beanLocator.getNames();
    for (String name : names) {
        LOG.debug(format("Processing bean locator bean named: %s", name));

        if (!isAcceptable(name)) {
            LOG.debug(format("Skipping bean %s", name));
            continue;
        }

        final Object bean = safeLocate(name);
        if (bean == null) {
            LOG.warn(format("Skipping bean %s (bean locator couldn't acquire a valid instance)", name));
            continue;
        }

        LOG.info(format("Copying bean definition %s", name));
        singletonBeanRegistry.registerSingleton(name, bean);
    }
}

From source file:ch.rasc.wampspring.config.DefaultWampConfiguration.java

@Bean
public MessageHandler annotationMethodMessageHandler(
        ConfigurableApplicationContext configurableApplicationContext) {

    AuthenticationHandler authenticationHandler = authenticationHandler();
    if (authenticationHandler != null) {
        configurableApplicationContext.getBeanFactory().registerSingleton("authenticationHandler",
                authenticationHandler);//from  ww w  .j  ava2s. c o m
    }

    WampAnnotationMethodMessageHandler messageHandler = new WampAnnotationMethodMessageHandler(
            clientInboundChannel(), clientOutboundChannel(), eventMessenger(), conversionService(),
            methodParameterConverter(), pathMatcher(), methodMessageHandlerMessageSelector());

    messageHandler.setAuthenticationRequiredGlobal(authenticationRequired());

    List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
    addArgumentResolvers(argumentResolvers);
    messageHandler.setCustomArgumentResolvers(argumentResolvers);

    return messageHandler;
}

From source file:org.sakaiproject.component.impl.ContextLoader.java

/**
 * Initialize the local ApplicationContext, link it to the shared context, and load shared definitions into the shared context.
 * //from   ww  w  .  ja v  a 2  s.  c  o m
 * @param servletContext
 *        current servlet context
 * @return the new WebApplicationContext
 * @throws BeansException
 *         if the context couldn't be initialized
 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws BeansException {
    WebApplicationContext rv = super.initWebApplicationContext(servletContext);

    // if we have a parent and any shared bean definitions, load them into the parent
    ConfigurableApplicationContext parent = (ConfigurableApplicationContext) rv.getParent();
    if (parent != null) {
        String sharedConfig = servletContext.getInitParameter(SHARED_LOCATION_PARAM);
        if (sharedConfig != null) {
            String[] locations = StringUtils.tokenizeToStringArray(sharedConfig,
                    ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS);
            if (locations != null) {
                XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
                        (BeanDefinitionRegistry) parent.getBeanFactory());

                for (int i = 0; i < locations.length; i++) {
                    try {
                        reader.loadBeanDefinitions(rv.getResources(locations[i]));
                    } catch (IOException e) {
                        M_log.warn("exception loading into parent: " + e);
                    }
                }
            }
        }
    }

    return rv;
}

From source file:cf.spring.config.YamlPropertyContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {//from w w w.  j a va2 s.  co m
        final ConfigurableEnvironment environment = applicationContext.getEnvironment();
        final Resource resource = applicationContext
                .getResource(environment.getProperty(locationProperty, locationDefault));
        final YamlDocument yamlDocument;
        LOGGER.info("Loading config from: {}", resource);
        yamlDocument = YamlDocument.load(resource);
        final MutablePropertySources propertySources = environment.getPropertySources();
        final PropertySource propertySource = new YamlPropertySource(name, yamlDocument);
        if (addFirst) {
            propertySources.addFirst(propertySource);
        } else {
            propertySources.addLast(propertySource);
        }

        applicationContext.getBeanFactory().registerSingleton(name, yamlDocument);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.sakaiproject.login.springframework.SakaiHomeContextLoader.java

/**
 * Initialize the local ApplicationContext, link it to the shared context, and load shared definitions into the shared context.
 *
 * @param servletContext current servlet context
 * @return the new WebApplicationContext
 * @throws org.springframework.beans.BeansException
 *          if the context couldn't be initialized
 *///  w  w w  .j a  v  a 2s . c om
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws BeansException {

    WebApplicationContext rv = super.initWebApplicationContext(servletContext);
    ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) rv;

    if (configurableApplicationContext != null) {
        String sakaiHomeLocation = servletContext.getInitParameter(SAKAI_HOME_LOCATION_PARAM);
        String servletContextName = rv.getServletContext().getServletContextName();
        if (sakaiHomeLocation == null || sakaiHomeLocation.length() == 0) {
            sakaiHomeLocation = servletContextName + SAKAI_HOME_CONTEXT_SUFFIX;
        }
        if (sakaiHomeLocation != null) {
            final String sakaiHomePath = ServerConfigurationService.getSakaiHomePath();

            String[] locations = StringUtils.tokenizeToStringArray(sakaiHomeLocation,
                    ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS);
            if (locations != null) {

                XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
                        (BeanDefinitionRegistry) configurableApplicationContext.getBeanFactory());

                for (int i = 0; i < locations.length; i++) {
                    String resourcePath = sakaiHomePath + locations[i];
                    M_log.debug(
                            servletContextName + " is attempting to load Spring beans from: " + resourcePath);
                    if (new File(resourcePath).exists()) {
                        reader.loadBeanDefinitions(new FileSystemResource(resourcePath));
                    } else {
                        M_log.info(servletContext + " startup is skipping introspection of the resource: "
                                + resourcePath + " because it does not exist.");
                    }
                }
            }
        }
    }

    return rv;
}

From source file:guru.qas.martini.jmeter.config.MartiniSpringConfiguration.java

@Override
public void testStarted() {
    synchronized (contextRef) {
        ConfigurableApplicationContext context = initializeContext();
        ConfigurableApplicationContext previous = contextRef.getAndSet(context);
        if (null != previous) {
            previous.close();/*from w ww.j ava 2 s . c o m*/
        }

        String hostname = JMeterUtils.getLocalHostName();
        String ip = JMeterUtils.getLocalHostIP();
        String name = super.getName();
        String id = context.getId();
        long startupDate = context.getStartupDate();
        String username = System.getProperty("user.name");

        ConfigurableEnvironment environment = context.getEnvironment();
        String[] activeProfiles = environment.getActiveProfiles();
        ArrayList<String> profiles = Lists.newArrayList(activeProfiles);

        Map<String, String> environmentVariables = this.getEnvironmentProperties().getArgumentsAsMap();

        SuiteIdentifier identifier = DefaultSuiteIdentifier.builder().setId(id).setStartupTimestamp(startupDate)
                .setName(name).setHostname(hostname).setHostAddress(ip).setUsername(username)
                .setProfiles(profiles).setEnvironmentVariables(environmentVariables).build();

        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        beanFactory.registerSingleton(BEAN_SUITE_IDENTIFIER, identifier);

        EventManager eventManager = context.getBean(EventManager.class);
        eventManager.publishBeforeSuite(this, identifier);
    }
}

From source file:com.modelmetrics.common.util.TestCaseWithLog.java

public BeanFactory getTestBeanFactory() {

    ConfigurableApplicationContext context = (ConfigurableApplicationContext) SpringBeanBroker.getBeanFactory();

    context.getBeanFactory().registerScope("session", new SessionScope());

    MockHttpServletRequest request = new MockHttpServletRequest();

    ServletRequestAttributes attributes = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(attributes);

    return context.getBeanFactory();

}