Example usage for org.springframework.beans.factory BeanFactory getBean

List of usage examples for org.springframework.beans.factory BeanFactory getBean

Introduction

In this page you can find the example usage for org.springframework.beans.factory BeanFactory getBean.

Prototype

<T> T getBean(Class<T> requiredType) throws BeansException;

Source Link

Document

Return the bean instance that uniquely matches the given object type, if any.

Usage

From source file:org.metamorfosis.model.project.InternalClassPathTest.java

public void testAddResource() throws Exception {
    log.debug("addResourcesDir");

    try {/*from  w w  w  .  j av a2 s  .  com*/
        BeanFactory factory = new XmlBeanFactory(new ClassPathResource("up-to-classpath.xml"));
        throw new AssertionError("No tendra que haber encontrado el recurso en el classpath");
    } catch (Throwable t) {
    }

    File resources = new File("./src/test/resources/up-to-classpath.xml");
    InternalClassPath.addResource(resources);

    BeanFactory factory = new XmlBeanFactory(new ClassPathResource("up-to-classpath.xml"));
    assertNotNull(factory);
    assertNotNull(factory.getBean("stringBean"));
}

From source file:org.mule.config.spring.jndi.SpringInitialContextFactory.java

public Context getInitialContext(Hashtable environment) throws NamingException {
    if (singleton != null) {
        return singleton;
    }/*  ww  w  . j ava2 s .co m*/
    Resource resource = null;
    Object value = environment.get(Context.PROVIDER_URL);
    String key = "jndi.xml";
    if (value == null) {
        resource = new ClassPathResource(key);
    } else {
        if (value instanceof Resource) {
            resource = (Resource) value;
        } else {
            ResourceEditor editor = new ResourceEditor();
            key = value.toString();
            editor.setAsText(key);
            resource = (Resource) editor.getValue();
        }
    }
    BeanFactory context = loadContext(resource, key);
    Context answer = (Context) context.getBean("jndi");
    if (answer == null) {
        log.warn("No JNDI context available in JNDI resource: " + resource);
        answer = new DefaultSpringJndiContext(environment, new ConcurrentHashMap());
    }
    return answer;
}

From source file:org.opens.tanaguru.cli.Tanaguru.java

/**
 *
 * @param tanaguruHome/*from  ww  w  . ja  va 2 s  . c o  m*/
 */
private void initServices(String tanaguruHome) {
    ApplicationContext springApplicationContext = new FileSystemXmlApplicationContext(
            tanaguruHome + "/" + APPLICATION_CONTEXT_FILE_PATH);
    BeanFactory springBeanFactory = springApplicationContext;
    auditService = (AuditService) springBeanFactory.getBean("auditService");
    auditDataService = (AuditDataService) springBeanFactory.getBean("auditDataService");
    webResourceDataService = (WebResourceDataService) springBeanFactory.getBean("webResourceDataService");
    webResourceStatisticsDataService = (WebResourceStatisticsDataService) springBeanFactory
            .getBean("webResourceStatisticsDataService");
    processResultDataService = (ProcessResultDataService) springBeanFactory.getBean("processResultDataService");
    processRemarkDataService = (ProcessRemarkDataService) springBeanFactory.getBean("processRemarkDataService");
    parameterDataService = (ParameterDataService) springBeanFactory.getBean("parameterDataService");
    parameterElementDataService = (ParameterElementDataService) springBeanFactory
            .getBean("parameterElementDataService");
    auditService.add(this);
}

From source file:org.sakaiproject.component.app.help.HelpManagerImpl.java

/**
 * Adds help for a specific locale//w  ww.  j  ava  2 s  .co m
 * @param path
 * @param locale
 */
private void addToolHelp(String path, String locale) {
    URL urlResource = null;
    String classpathUrl = null;

    String sakaiHomePath = serverConfigurationService.getSakaiHomePath();
    String localHelpPath = sakaiHomePath + serverConfigurationService.getString("help.localpath", "/help/");

    File localFile = null;

    // find default help file
    if (locale.equals(DEFAULT_LOCALE)) {
        classpathUrl = path + "/" + HELP_BASENAME + ".xml";

        localFile = new File(localHelpPath + classpathUrl);
        if (localFile.isFile()) {
            try {
                urlResource = localFile.toURI().toURL();
            } catch (MalformedURLException e) {
                urlResource = getClass().getResource(classpathUrl);
            }
        } else {
            urlResource = getClass().getResource(classpathUrl);
        }
    }

    // find localized help file
    else {
        classpathUrl = path + "/" + HELP_BASENAME + "_" + locale + ".xml";
        localFile = new File(localHelpPath + classpathUrl);
        if (localFile.isFile()) {
            try {
                urlResource = localFile.toURI().toURL();
            } catch (MalformedURLException e) {
                urlResource = getClass().getResource(classpathUrl);
            }
        } else {
            urlResource = getClass().getResource(classpathUrl);
        }

        // If language/region help file not found, look for language-only help file
        if (urlResource == null) {
            Locale nextLocale = getLocaleFromString(locale);
            classpathUrl = path + "/" + HELP_BASENAME + "_" + nextLocale.getLanguage() + ".xml";
            localFile = new File(localHelpPath + classpathUrl);
            if (localFile.isFile()) {
                try {
                    urlResource = localFile.toURI().toURL();
                } catch (MalformedURLException e) {
                    urlResource = getClass().getResource(classpathUrl);
                }
            } else {
                urlResource = getClass().getResource(classpathUrl);
            }
        }

        // If language-only help file not found, look for default help file
        if (urlResource == null) {
            classpathUrl = path + "/" + HELP_BASENAME + ".xml";
            localFile = new File(localHelpPath + classpathUrl);
            if (localFile.isFile()) {
                try {
                    urlResource = localFile.toURI().toURL();
                } catch (MalformedURLException e) {
                    urlResource = getClass().getResource(classpathUrl);
                }
            } else {
                urlResource = getClass().getResource(classpathUrl);
            }
        }
    }

    // Url exists?
    if (urlResource != null) {
        TableOfContentsBean localizedToc;

        // Add this tool categories to this tool toc
        try {
            org.springframework.core.io.Resource resource = new UrlResource(urlResource);
            BeanFactory beanFactory = new XmlBeanFactory(resource);
            TableOfContents tocTemp = (TableOfContents) beanFactory.getBean(TOC_API);
            Set<Category> categories = tocTemp.getCategories();
            storeRecursive(categories);

            // Get localized toc
            if (toc.containsKey(locale)) {
                localizedToc = toc.get(locale);
            } else { // Create and add localized toc
                localizedToc = new TableOfContentsBean();
                toc.put(locale, localizedToc);
            }

            // Update localized toc categories
            localizedToc.getCategories().addAll(categories);
        } catch (Exception e) {
            LOG.warn("Unable to load help index from " + classpathUrl + " : " + e.getMessage());
        }
    }
}

From source file:org.sakaiproject.tool.assessment.api.spring.FactoryUtil.java

public static SamigoApiFactory lookup() throws Exception {
    // the instance is provided by Spring-injection
    if (useLocator) {

        SpringBeanLocator locator = SpringBeanLocator.getInstance();
        return (SamigoApiFactory) locator.getBean("samigoApiFactory");
    } else // unit testing
    {//from   w ww.  ja  v a  2  s  .  co  m
        Resource res = new ClassPathResource(CONFIGURATION);
        BeanFactory factory = new XmlBeanFactory(res);
        return (SamigoApiFactory) factory.getBean("samigoApiFactory");
    }

}

From source file:org.sakaiproject.tool.assessment.integration.context.spring.FactoryUtil.java

public static IntegrationContextFactory lookup() throws Exception {
    // the instance is provided by Spring-injection
    if (useLocator) {

        SpringBeanLocator locator = SpringBeanLocator.getInstance();
        return (IntegrationContextFactory) locator.getBean("integrationContextFactory");
    } else // unit testing
    {//  w ww.  j  a v  a2s . com
        Resource res = new ClassPathResource(CONFIGURATION);
        BeanFactory factory = new XmlBeanFactory(res);
        return (IntegrationContextFactory) factory.getBean("integrationContextFactory");
    }

}

From source file:org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.java

/**
 * Resolves the specified interceptor names to Advisor objects.
 * @see #setInterceptorNames//from  www. j  av a 2  s . co  m
 */
private Advisor[] resolveInterceptorNames() {
    BeanFactory bf = this.beanFactory;
    ConfigurableBeanFactory cbf = (bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null);
    List<Advisor> advisors = new ArrayList<>();
    for (String beanName : this.interceptorNames) {
        if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {
            Assert.state(bf != null, "BeanFactory required for resolving interceptor names");
            Object next = bf.getBean(beanName);
            advisors.add(this.advisorAdapterRegistry.wrap(next));
        }
    }
    return advisors.toArray(new Advisor[advisors.size()]);
}

From source file:org.springframework.aop.interceptor.AsyncExecutionAspectSupport.java

/**
 * Retrieve or build a default executor for this advice instance.
 * An executor returned from here will be cached for further use.
 * <p>The default implementation searches for a unique {@link TaskExecutor} bean
 * in the context, or for an {@link Executor} bean named "taskExecutor" otherwise.
 * If neither of the two is resolvable, this implementation will return {@code null}.
 * @param beanFactory the BeanFactory to use for a default executor lookup
 * @return the default executor, or {@code null} if none available
 * @since 4.2.6/*from   ww  w . j  a va  2  s.c o  m*/
 * @see #findQualifiedExecutor(BeanFactory, String)
 * @see #DEFAULT_TASK_EXECUTOR_BEAN_NAME
 */
@Nullable
protected Executor getDefaultExecutor(@Nullable BeanFactory beanFactory) {
    if (beanFactory != null) {
        try {
            // Search for TaskExecutor bean... not plain Executor since that would
            // match with ScheduledExecutorService as well, which is unusable for
            // our purposes here. TaskExecutor is more clearly designed for it.
            return beanFactory.getBean(TaskExecutor.class);
        } catch (NoUniqueBeanDefinitionException ex) {
            logger.debug("Could not find unique TaskExecutor bean", ex);
            try {
                return beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, Executor.class);
            } catch (NoSuchBeanDefinitionException ex2) {
                if (logger.isInfoEnabled()) {
                    logger.info("More than one TaskExecutor bean found within the context, and none is named "
                            + "'taskExecutor'. Mark one of them as primary or name it 'taskExecutor' (possibly "
                            + "as an alias) in order to use it for async processing: "
                            + ex.getBeanNamesFound());
                }
            }
        } catch (NoSuchBeanDefinitionException ex) {
            logger.debug("Could not find default TaskExecutor bean", ex);
            try {
                return beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, Executor.class);
            } catch (NoSuchBeanDefinitionException ex2) {
                logger.info("No task executor bean found for async processing: "
                        + "no bean of type TaskExecutor and no bean named 'taskExecutor' either");
            }
            // Giving up -> either using local default executor or none at all...
        }
    }
    return null;
}

From source file:org.springframework.beans.factory.access.el.SpringBeanELResolver.java

@Override
public Object getValue(ELContext elContext, Object base, Object property) throws ELException {
    if (base == null) {
        String beanName = property.toString();
        BeanFactory bf = getBeanFactory(elContext);
        if (bf.containsBean(beanName)) {
            if (logger.isTraceEnabled()) {
                logger.trace("Successfully resolved variable '" + beanName + "' in Spring BeanFactory");
            }/*from   w  w w .  j  av a2 s.  c  o  m*/
            elContext.setPropertyResolved(true);
            return bf.getBean(beanName);
        }
    }
    return null;
}

From source file:org.springframework.beans.factory.xml.XmlBeanFactoryTests.java

private void lookupOverrideMethodsWithSetterInjection(BeanFactory xbf, String beanName, boolean singleton) {
    OverrideOneMethod oom = (OverrideOneMethod) xbf.getBean(beanName);

    if (singleton) {
        assertSame(oom, xbf.getBean(beanName));
    } else {/*from   www .  j  a va  2 s.  co  m*/
        assertNotSame(oom, xbf.getBean(beanName));
    }

    TestBean jenny1 = oom.getPrototypeDependency();
    assertEquals("Jenny", jenny1.getName());
    TestBean jenny2 = oom.getPrototypeDependency();
    assertEquals("Jenny", jenny2.getName());
    assertNotSame(jenny1, jenny2);

    // Check that the bean can invoke the overridden method on itself
    // This differs from Spring's AOP support, which has a distinct notion
    // of a "target" object, meaning that the target needs explicit knowledge
    // of AOP proxying to invoke an advised method on itself.
    TestBean jenny3 = oom.invokesOverriddenMethodOnSelf();
    assertEquals("Jenny", jenny3.getName());
    assertNotSame(jenny1, jenny3);

    // Now try protected method, and singleton
    TestBean dave1 = oom.protectedOverrideSingleton();
    assertEquals("David", dave1.getName());
    TestBean dave2 = oom.protectedOverrideSingleton();
    assertEquals("David", dave2.getName());
    assertSame(dave1, dave2);
}