Example usage for org.springframework.beans.factory BeanFactoryUtils beanNamesForTypeIncludingAncestors

List of usage examples for org.springframework.beans.factory BeanFactoryUtils beanNamesForTypeIncludingAncestors

Introduction

In this page you can find the example usage for org.springframework.beans.factory BeanFactoryUtils beanNamesForTypeIncludingAncestors.

Prototype

public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, Class<?> type) 

Source Link

Document

Get all bean names for the given type, including those defined in ancestor factories.

Usage

From source file:org.springframework.batch.admin.BootstrapTests.java

@Test
public void testServletConfiguration() throws Exception {
    ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext(
            "classpath:/org/springframework/batch/admin/web/resources/webapp-config.xml");
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "classpath:/org/springframework/batch/admin/web/resources/servlet-config.xml" },
            parent);/*from   ww w  .  jav a 2  s  . c  om*/

    assertTrue(context.containsBean("jobRepository"));
    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(),
            JobController.class);
    assertEquals(1, beanNames.length);

    MenuManager menuManager = context.getBean(MenuManager.class);
    assertEquals(4, menuManager.getMenus().size());

    context.refresh();

    ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext(
            new String[] { "classpath:/test-job-context.xml" }, parent);
    Job job = child.getBean(Job.class);
    final JobExecution jobExecution = parent.getBean(JobLauncher.class).run(job, new JobParameters());

    new DirectPoller<BatchStatus>(100).poll(new Callable<BatchStatus>() {
        public BatchStatus call() throws Exception {
            BatchStatus status = jobExecution.getStatus();
            if (status.isLessThan(BatchStatus.STOPPED) && status != BatchStatus.COMPLETED) {
                return null;
            }
            return status;
        }
    }).get(2000, TimeUnit.MILLISECONDS);

    HomeController metaData = new HomeController();
    metaData.setApplicationContext(context);
    metaData.afterPropertiesSet();
    MockHttpServletRequest request = new MockHttpServletRequest();
    ModelMap model = new ModelMap();
    metaData.getResources(request, model);
    @SuppressWarnings("unchecked")
    List<ResourceInfo> resources = (List<ResourceInfo>) model.get("resources");
    StringBuilder content = new StringBuilder();
    for (ResourceInfo resourceInfo : resources) {
        content.append(resourceInfo.getMethod() + resourceInfo.getUrl() + "=\n");
    }
    FileUtils.writeStringToFile(new File("target/resources.properties"), content.toString());

    HomeController home = context.getBean(HomeController.class);
    // System.err.println(home.getUrlPatterns());
    assertTrue(home.getUrlPatterns().contains("/jobs/{jobName}"));

    String message = context.getMessage("GET/jobs/{jobName}", new Object[0], Locale.getDefault());
    assertTrue("No message for /jobs/{jobName}", StringUtils.hasText(message));

    child.close();
    context.close();
    parent.close();

    assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());

}

From source file:org.springframework.data.hadoop.scripting.HdfsScriptRunner.java

private Configuration detectCfg(String variableName) {
    if (configuration != null) {
        return configuration;
    }/*  ww w  . j  av  a 2 s .c  o  m*/

    String defaultName = "hadoopConfiguration";
    Class<Configuration> defaultType = Configuration.class;

    if (ctx.containsBean(defaultName))
        return ctx.getBean(defaultName, defaultType);
    String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, defaultType);
    if (names != null && names.length == 1) {
        return ctx.getBean(names[0], defaultType);
    }

    log.warn(String.format(
            "No Hadoop Configuration detected; not binding Configuration as variable '%s' to script",
            variableName));
    return null;
}

From source file:org.springframework.data.hadoop.scripting.HdfsScriptRunner.java

private HdfsResourceLoader detectHdfsRL(String variableName, Configuration cfg) {
    String defaultName = "hadoopResourceLoader";
    Class<HdfsResourceLoader> defaultType = HdfsResourceLoader.class;

    if (ctx.containsBean(defaultName))
        return ctx.getBean(defaultName, defaultType);
    String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, defaultType);
    if (names != null && names.length == 1) {
        return ctx.getBean(names[0], defaultType);
    }//from ww w.  j  a v  a 2  s  . c o m

    // sanity check
    if (cfg == null) {
        log.warn(String.format(
                "No Hadoop Configuration or ResourceLoader detected; not binding variable '%s' to script",
                variableName));
        return null;
    }

    // create one instance
    return new HdfsResourceLoader(cfg);
}

From source file:org.springframework.data.hadoop.scripting.HdfsScriptRunner.java

private Object detectFS(String variableName, Configuration detectedCfg) {
    String defaultName = "hadoopFs";
    Class<?> defaultType = FileSystem.class;

    if (ctx.containsBean(defaultName)) {
        FileSystem fs = (FileSystem) ctx.getBean(defaultName, defaultType);
        return (fs instanceof SimplerFileSystem ? fs : new SimplerFileSystem(fs));
    }//from w  w  w.  j a  va2s .  c  o m

    String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, defaultType);
    if (names != null && names.length == 1) {
        return ctx.getBean(names[0], defaultType);
    }

    // sanity check
    if (detectedCfg == null) {
        log.warn(String.format(
                "No Hadoop Configuration or FileSystem detected; not binding variable '%s' to script",
                variableName));
        return null;
    }

    try {
        FileSystem fs = FileSystem.get(detectedCfg);
        return (fs instanceof SimplerFileSystem ? fs : new SimplerFileSystem(fs));
    } catch (IOException ex) {
        log.warn(String.format("Cannot create HDFS file system'; not binding variable '%s' to script",
                defaultName, defaultType, variableName), ex);
    }

    return null;
}

From source file:org.springframework.orm.jpa.EntityManagerFactoryUtils.java

/**
 * Find an EntityManagerFactory with the given name in the given
 * Spring application context (represented as ListableBeanFactory).
 * <p>The specified unit name will be matched against the configured
 * persistence unit, provided that a discovered EntityManagerFactory
 * implements the {@link EntityManagerFactoryInfo} interface. If not,
 * the persistence unit name will be matched against the Spring bean name,
 * assuming that the EntityManagerFactory bean names follow that convention.
 * <p>If no unit name has been given, this method will search for a default
 * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
 * @param beanFactory the ListableBeanFactory to search
 * @param unitName the name of the persistence unit (may be {@code null} or empty,
 * in which case a single bean of type EntityManagerFactory will be searched for)
 * @return the EntityManagerFactory//from  w  w w. j  a va  2 s  .c o m
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 * @see EntityManagerFactoryInfo#getPersistenceUnitName()
 */
public static EntityManagerFactory findEntityManagerFactory(ListableBeanFactory beanFactory,
        @Nullable String unitName) throws NoSuchBeanDefinitionException {

    Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
    if (StringUtils.hasLength(unitName)) {
        // See whether we can find an EntityManagerFactory with matching persistence unit name.
        String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory,
                EntityManagerFactory.class);
        for (String candidateName : candidateNames) {
            EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
            if (emf instanceof EntityManagerFactoryInfo) {
                if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
                    return emf;
                }
            }
        }
        // No matching persistence unit found - simply take the EntityManagerFactory
        // with the persistence unit name as bean name (by convention).
        return beanFactory.getBean(unitName, EntityManagerFactory.class);
    } else {
        // Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
        return beanFactory.getBean(EntityManagerFactory.class);
    }
}

From source file:org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration.java

@SuppressWarnings("unchecked")
private <T> T lazyBean(Class<T> interfaceName) {
    LazyInitTargetSource lazyTargetSource = new LazyInitTargetSource();
    String[] beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext,
            interfaceName);// w w w  .j  ava  2s .  c o  m
    if (beanNamesForType.length == 0) {
        return null;
    }
    String beanName;
    if (beanNamesForType.length > 1) {
        List<String> primaryBeanNames = Arrays.stream(beanNamesForType)
                .filter(i -> applicationContext instanceof ConfigurableApplicationContext)
                .filter(n -> ((ConfigurableApplicationContext) applicationContext).getBeanFactory()
                        .getBeanDefinition(n).isPrimary())
                .collect(Collectors.toList());

        Assert.isTrue(primaryBeanNames.size() != 0, () -> "Found " + beanNamesForType.length
                + " beans for type " + interfaceName + ", but none marked as primary");
        Assert.isTrue(primaryBeanNames.size() == 1, () -> "Found " + primaryBeanNames.size()
                + " beans for type " + interfaceName + " marked as primary");
        beanName = primaryBeanNames.get(0);
    } else {
        beanName = beanNamesForType[0];
    }

    lazyTargetSource.setTargetBeanName(beanName);
    lazyTargetSource.setBeanFactory(applicationContext);
    ProxyFactoryBean proxyFactory = new ProxyFactoryBean();
    proxyFactory = objectPostProcessor.postProcess(proxyFactory);
    proxyFactory.setTargetSource(lazyTargetSource);
    return (T) proxyFactory.getObject();
}

From source file:org.springframework.web.method.ControllerAdviceBean.java

/**
 * Find the names of beans annotated with
 * {@linkplain ControllerAdvice @ControllerAdvice} in the given
 * ApplicationContext and wrap them as {@code ControllerAdviceBean} instances.
 *///from   ww  w  . ja  va 2  s . co m
public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) {
    List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>();
    for (String name : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class)) {
        if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
            beans.add(new ControllerAdviceBean(name, applicationContext));
        }
    }
    return beans;
}

From source file:org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.java

/**
 * Scan beans in the ApplicationContext, detect and register handler methods.
 * @see #isHandler(Class)//from w ww  . j  av  a2  s.  c  o m
 * @see #getMappingForMethod(Method, Class)
 * @see #handlerMethodsInitialized(Map)
 */
protected void initHandlerMethods() {

    String[] beanNames = (this.detectHandlerMethodsInAncestorContexts
            ? BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class)
            : obtainApplicationContext().getBeanNamesForType(Object.class));

    for (String beanName : beanNames) {
        if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
            Class<?> beanType = null;
            try {
                beanType = obtainApplicationContext().getType(beanName);
            } catch (Throwable ex) {
                // An unresolvable bean type, probably from a lazy bean - let's ignore it.
                if (logger.isTraceEnabled()) {
                    logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
                }
            }
            if (beanType != null && isHandler(beanType)) {
                detectHandlerMethods(beanName);
            }
        }
    }
    handlerMethodsInitialized(getHandlerMethods());
}