Example usage for org.springframework.context.support GenericApplicationContext getBeanFactory

List of usage examples for org.springframework.context.support GenericApplicationContext getBeanFactory

Introduction

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

Prototype

@Override
public final ConfigurableListableBeanFactory getBeanFactory() 

Source Link

Document

Return the single internal BeanFactory held by this context (as ConfigurableListableBeanFactory).

Usage

From source file:com.opengamma.component.factory.AbstractSpringComponentFactory.java

/**
 * Registers the spring context to be stopped at the end of the application.
 * <p>//from  www  . j  a va 2  s .c  o m
 * This will call {@link ConfigurableListableBeanFactory#destroySingletons()}
 * at the end of the application.
 * 
 * @param repo  the repository to register in, not null
 * @param appContext  the Spring context, not null
 */
protected void registerSpringLifecycleStop(ComponentRepository repo, GenericApplicationContext appContext) {
    repo.registerLifecycleStop(appContext.getBeanFactory(), "destroySingletons");
}

From source file:com.retroduction.carma.application.CarmaTestExecuter.java

public Summary executeTests() {

    CarmaDriverSetup setup = new CarmaDriverSetup();
    Properties customProps = new Properties();
    try {//from   ww w . jav a  2  s . c o  m
        customProps.load(new FileInputStream(this.configFile));

    } catch (IOException e) {
        throw new CarmaException("Failed to load configuration", e);
    }

    // merge multiple bean definition sources into application context
    GenericApplicationContext factory = new GenericApplicationContext();

    customProps.setProperty(ICoreConfigConsts.BEAN_REPORTFILE, this.reportFile.getPath());

    // configure maven specific bean references and add beans to parent
    // factory
    // the names in the parent factory should be unique and not overridden
    // by children, otherwise they would have no effect

    customProps.setProperty("project.classesdir.source", BEAN_MAVEN_PROJECT_CLASSES_DIR);
    factory.getBeanFactory().registerSingleton(BEAN_MAVEN_PROJECT_CLASSES_DIR, this.classesDir);

    customProps.setProperty("project.testclassesdir.source", BEAN_MAVEN_PROJECT_TESTCLASSES_DIR);
    factory.getBeanFactory().registerSingleton(BEAN_MAVEN_PROJECT_TESTCLASSES_DIR, this.testClassesDir);

    customProps.setProperty("project.libraries.source", BEAN_MAVEN_PROJECT_LIBRARIES);
    factory.getBeanFactory().registerSingleton(BEAN_MAVEN_PROJECT_LIBRARIES, this.dependencyClassPathUrls);

    setup.setParentContext(factory);
    setup.addCustomConfiguration(customProps);

    // add runtime parameters
    if (this.reportFile.getParentFile() != null) {
        this.reportFile.getParentFile().mkdirs();
    }

    factory.refresh();
    ApplicationContext ctx = setup.getApplicationContext();
    SummaryCreatorEventListener summaryCreator = new SummaryCreatorEventListener();
    ((CompositeEventListener) ctx.getBean("eventListener")).getListeners().add(summaryCreator);

    Core driver = setup.getDriver();
    driver.execute();

    Summary sum = summaryCreator.createSummary();
    return sum;
}

From source file:de.hybris.platform.btgcockpit.service.BTGCockpitServiceTest.java

public void initApplicationContext() {
    final GenericApplicationContext context = new GenericApplicationContext();
    context.setResourceLoader(new DefaultResourceLoader(Registry.class.getClassLoader()));
    context.setClassLoader(Registry.class.getClassLoader());
    context.getBeanFactory().setBeanClassLoader(Registry.class.getClassLoader());
    context.setParent(Registry.getGlobalApplicationContext());
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.setDocumentReaderClass(ScopeTenantIgnoreDocReader.class);
    xmlReader.setBeanClassLoader(Registry.class.getClassLoader());
    xmlReader.loadBeanDefinitions(getSpringConfigurationLocations());
    context.refresh();//from   ww w  .ja  v  a2 s  .co m
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
    this.applicationContex = context;
}

From source file:com.opengamma.component.factory.AbstractSpringComponentFactory.java

/**
 * Creates the application context./*from   www .j  a  va  2  s. c  o  m*/
 * 
 * @param repo  the component repository, not null
 * @return the Spring application context, not null
 */
protected GenericApplicationContext createApplicationContext(ComponentRepository repo) {
    Resource springFile = getSpringFile();
    try {
        repo.getLogger().logDebug("  Spring file: " + springFile.getURI());
    } catch (Exception ex) {
        // ignore
    }

    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    GenericApplicationContext appContext = new GenericApplicationContext(beanFactory);

    PropertyPlaceholderConfigurer properties = new PropertyPlaceholderConfigurer();
    properties.setLocation(getPropertiesFile());

    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    beanDefinitionReader.setValidating(true);
    beanDefinitionReader.setResourceLoader(appContext);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(appContext));
    beanDefinitionReader.loadBeanDefinitions(springFile);

    appContext.getBeanFactory().registerSingleton("injectedProperties", properties);
    appContext.getBeanFactory().registerSingleton("componentRepository", repo);

    appContext.refresh();
    return appContext;
}

From source file:it.scoppelletti.programmerpower.console.spring.ConsoleApplicationRunner.java

/**
 * Inizializza il contesto dell&rsquo;applicazione.
 * /*  w ww.  j av a2s.  co m*/
 * @param  ui Interfaccia utente.
 * @return    Oggetto.
 */
private GenericApplicationContext initApplicationContext(UserInterfaceProvider ui) {
    SingletonBeanRegistry beanRegistry;
    GenericApplicationContext ctx = null;
    GenericApplicationContext applCtx;
    XmlBeanDefinitionReader reader;
    ConfigurableEnvironment env;
    PropertySource<?> propSource;
    MutablePropertySources propSources;

    try {
        ctx = new GenericApplicationContext();
        reader = new XmlBeanDefinitionReader(ctx);
        reader.loadBeanDefinitions(ConsoleApplicationRunner.CONSOLE_CONTEXT);
        reader.loadBeanDefinitions(initApplicationContextResourceName());

        beanRegistry = ctx.getBeanFactory();
        beanRegistry.registerSingleton(ConsoleApplicationRunner.BEAN_NAME, this);
        beanRegistry.registerSingleton(UserInterfaceProvider.BEAN_NAME, ui);

        env = ctx.getEnvironment();

        // Acquisisco gli eventuali profili configurati prima di aggiungere
        // quello di Programmer Power
        env.getActiveProfiles();

        env.addActiveProfile(ConsoleApplicationRunner.PROFILE);

        propSources = env.getPropertySources();

        propSources.addFirst(new ConsolePropertySource(ConsolePropertySource.class.getName(), this));

        propSource = BeanConfigUtils.loadPropertySource();
        if (propSource != null) {
            propSources.addFirst(propSource);
        }

        ctx.refresh();
        applCtx = ctx;
        ctx = null;
    } finally {
        if (ctx != null) {
            ctx.close();
            ctx = null;
        }
    }

    return applCtx;
}

From source file:grails.spring.BeanBuilder.java

/**
 * Register a set of beans with the given bean registry. Most
 * application contexts are bean registries.
 *//*from  w  w w.  j  ava 2  s. com*/
public void registerBeans(BeanDefinitionRegistry registry) {
    finalizeDeferredProperties();

    if (registry instanceof GenericApplicationContext) {
        GenericApplicationContext ctx = (GenericApplicationContext) registry;
        ctx.setClassLoader(classLoader);
        ctx.getBeanFactory().setBeanClassLoader(classLoader);
    }

    springConfig.registerBeansWithRegistry(registry);
}

From source file:nz.co.senanque.madura.bundle.BundleRootImpl.java

public void init(DefaultListableBeanFactory ownerBeanFactory, Properties properties, ClassLoader cl,
        Map<String, Object> inheritableBeans) {
    m_properties = properties;/*from   ww w .  ja v  a2 s  .  c  om*/
    m_inheritableBeans = inheritableBeans;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(cl);
    m_classLoader = cl;
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    String contextPath = properties.getProperty("Bundle-Context", "/bundle-spring.xml");
    m_logger.debug("loading context: {}", contextPath);
    ClassPathResource classPathResource = new ClassPathResource(contextPath, cl);
    xmlReader.loadBeanDefinitions(classPathResource);
    PropertyPlaceholderConfigurer p = new PropertyPlaceholderConfigurer();
    p.setProperties(properties);
    ctx.addBeanFactoryPostProcessor(p);
    if (m_logger.isDebugEnabled()) {
        dumpClassLoader(cl);
    }
    for (Map.Entry<String, Object> entry : inheritableBeans.entrySet()) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(InnerBundleFactory.class);
        beanDefinitionBuilder.addPropertyValue("key", entry.getKey());
        beanDefinitionBuilder.addPropertyValue("object", inheritableBeans.get(entry.getKey()));
        ctx.registerBeanDefinition(entry.getKey(), beanDefinitionBuilder.getBeanDefinition());
    }
    Scope scope = ownerBeanFactory.getRegisteredScope("session");
    if (scope != null) {
        ctx.getBeanFactory().registerScope("session", scope);
    }
    ctx.refresh();
    m_applicationContext = ctx;
    Thread.currentThread().setContextClassLoader(classLoader);
}

From source file:org.codehaus.groovy.grails.plugins.DefaultGrailsPlugin.java

private void invokeOnChangeListener(Map event) {
    onChangeListener.setDelegate(this);
    onChangeListener.call(new Object[] { event });

    if (!(applicationContext instanceof GenericApplicationContext)) {
        return;//from www.  j a  v a  2  s .co  m
    }

    // Apply any factory post processors in case the change listener has changed any
    // bean definitions (GRAILS-5763)
    GenericApplicationContext ctx = (GenericApplicationContext) applicationContext;
    ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory();
    for (BeanFactoryPostProcessor postProcessor : ctx.getBeanFactoryPostProcessors()) {
        try {
            postProcessor.postProcessBeanFactory(beanFactory);
        } catch (IllegalStateException e) {
            // post processor doesn't allow running again, just continue
        }
    }
}

From source file:org.pentaho.platform.plugin.services.pluginmgr.DefaultPluginManager.java

/**
 * Initializes a bean factory for serving up instance of plugin classes.
 *
 * @return an instance of the factory that allows callers to continue to define more beans on it programmatically
 *//*  w w w  .  j  a  va  2  s . c  o m*/
protected void initializeBeanFactory(final IPlatformPlugin plugin, final ClassLoader loader)
        throws PlatformPluginRegistrationException {

    if (!(loader instanceof PluginClassLoader)) {
        logger.warn(
                "Can't determine plugin dir to load spring file because classloader is not of type PluginClassLoader.  "
                        //$NON-NLS-1$
                        + "This is since we are probably in a unit test"); //$NON-NLS-1$
        return;
    }

    //
    // Get the native factory (the factory that comes preconfigured via either Spring bean files or via JUnit test
    //
    BeanFactory nativeBeanFactory = getNativeBeanFactory(plugin, loader);

    //
    // Now create the definable factory for accepting old style bean definitions from IPluginProvider
    //

    GenericApplicationContext beanFactory = null;
    if (nativeBeanFactory != null && nativeBeanFactory instanceof GenericApplicationContext) {
        beanFactory = (GenericApplicationContext) nativeBeanFactory;
    } else {
        beanFactory = new GenericApplicationContext();
        beanFactory.setClassLoader(loader);
        beanFactory.getBeanFactory().setBeanClassLoader(loader);

        if (nativeBeanFactory != null) {
            beanFactory.getBeanFactory().setParentBeanFactory(nativeBeanFactory);
        }
    }

    beanFactoryMap.put(plugin.getId(), beanFactory);

    //
    // Register any beans defined via the pluginProvider
    //

    // we do not have to synchronize on the bean set here because the
    // map that backs the set is never modified after the plugin has
    // been made available to the plugin manager
    for (PluginBeanDefinition def : plugin.getBeans()) {
        // register by classname if id is null
        def.setBeanId((def.getBeanId() == null) ? def.getClassname() : def.getBeanId());
        assertUnique(plugin.getId(), def.getBeanId());
        // defining plugin beans the old way through the plugin provider ifc supports only prototype scope
        BeanDefinition beanDef = BeanDefinitionBuilder.rootBeanDefinition(def.getClassname())
                .setScope(BeanDefinition.SCOPE_PROTOTYPE).getBeanDefinition();
        beanFactory.registerBeanDefinition(def.getBeanId(), beanDef);
    }

    StandaloneSpringPentahoObjectFactory pentahoFactory = new StandaloneSpringPentahoObjectFactory(
            "Plugin Factory ( " + plugin.getId() + " )");
    pentahoFactory.init(null, beanFactory);

}

From source file:org.springframework.amqp.rabbit.core.RabbitAdminTests.java

@Test
public void testNoFailOnStartupWithMissingBroker() throws Exception {
    SingleConnectionFactory connectionFactory = new SingleConnectionFactory("foo");
    connectionFactory.setPort(434343);/*from w  w w . java  2  s .  co  m*/
    GenericApplicationContext applicationContext = new GenericApplicationContext();
    applicationContext.getBeanFactory().registerSingleton("foo", new Queue("queue"));
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    rabbitAdmin.setApplicationContext(applicationContext);
    rabbitAdmin.setAutoStartup(true);
    rabbitAdmin.afterPropertiesSet();
    connectionFactory.destroy();
}