Example usage for org.springframework.context ApplicationContext getBeansOfType

List of usage examples for org.springframework.context ApplicationContext getBeansOfType

Introduction

In this page you can find the example usage for org.springframework.context ApplicationContext getBeansOfType.

Prototype

<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;

Source Link

Document

Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.

Usage

From source file:org.springframework.batch.integration.samples.payments.util.SpringIntegrationUtils.java

/**
 * Helper Method to dynamically determine and display input and output
 * directories as defined in the Spring Integration context.
 *
 * @param context Spring Application Context
 *///www .j  a v  a  2  s  . com
public static void displayDirectories(final ApplicationContext context) {

    final Map<String, FileReadingMessageSource> fileReadingMessageSources = context
            .getBeansOfType(FileReadingMessageSource.class);
    final List<String> inputDirectories = new ArrayList<String>();

    for (final FileReadingMessageSource messageHandler : fileReadingMessageSources.values()) {
        final File inDir = (File) new DirectFieldAccessor(messageHandler).getPropertyValue("directory");
        inputDirectories.add(inDir.getAbsolutePath());
    }

    final Map<String, FileWritingMessageHandler> fileWritingMessageHandlers = context
            .getBeansOfType(FileWritingMessageHandler.class);
    final List<String> outputDirectories = new ArrayList<String>();

    for (final FileWritingMessageHandler messageHandler : fileWritingMessageHandlers.values()) {
        final Expression outDir = (Expression) new DirectFieldAccessor(messageHandler)
                .getPropertyValue("destinationDirectoryExpression");
        outputDirectories.add(outDir.getExpressionString());
    }

    final StringBuilder stringBuilder = new StringBuilder();

    for (final String inputDirectory : inputDirectories) {
        stringBuilder.append("\n    Input directory is : '" + inputDirectory + "'");
    }

    for (final String outputDirectory : outputDirectories) {
        stringBuilder.append("\n    Output directory is: '" + outputDirectory + "'");
    }

    stringBuilder.append("\n\n=========================================================");

    logger.info(stringBuilder.toString());

}

From source file:org.springframework.boot.actuate.context.properties.ConfigurationPropertiesReportEndpoint.java

private ConfigurationBeanFactoryMetadata getBeanFactoryMetadata(ApplicationContext context) {
    Map<String, ConfigurationBeanFactoryMetadata> beans = context
            .getBeansOfType(ConfigurationBeanFactoryMetadata.class);
    if (beans.size() == 1) {
        return beans.values().iterator().next();
    }//from   w w  w.j a  v a 2 s.c o  m
    return null;
}

From source file:org.springframework.boot.actuate.endpoint.ConfigurationPropertiesReportEndpoint.java

private ConfigurationBeanFactoryMetaData getBeanFactoryMetaData(ApplicationContext context) {
    Map<String, ConfigurationBeanFactoryMetaData> beans = context
            .getBeansOfType(ConfigurationBeanFactoryMetaData.class);
    if (beans.size() == 1) {
        return beans.values().iterator().next();
    }// w w w.  j  av  a2s  .c o m
    return null;
}

From source file:org.springframework.boot.SpringApplication.java

private void callRunners(ApplicationContext context, ApplicationArguments args) {
    List<Object> runners = new ArrayList<Object>();
    runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
    runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
    AnnotationAwareOrderComparator.sort(runners);
    for (Object runner : new LinkedHashSet<Object>(runners)) {
        if (runner instanceof ApplicationRunner) {
            callRunner((ApplicationRunner) runner, args);
        }//from   w w  w . j ava 2s  . c  om
        if (runner instanceof CommandLineRunner) {
            callRunner((CommandLineRunner) runner, args);
        }
    }
}

From source file:org.springframework.boot.SpringApplication.java

/**
 * Static helper that can be used to exit a {@link SpringApplication} and obtain a
 * code indicating success (0) or otherwise. Does not throw exceptions but should
 * print stack traces of any encountered. Applies the specified
 * {@link ExitCodeGenerator} in addition to any Spring beans that implement
 * {@link ExitCodeGenerator}. In the case of multiple exit codes the highest value
 * will be used (or if all values are negative, the lowest value will be used)
 * @param context the context to close if possible
 * @param exitCodeGenerators exist code generators
 * @return the outcome (0 if successful)
 *///from   w ww . ja v  a2s.co m
public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) {
    int exitCode = 0;
    try {
        try {
            List<ExitCodeGenerator> generators = new ArrayList<ExitCodeGenerator>();
            generators.addAll(Arrays.asList(exitCodeGenerators));
            generators.addAll(context.getBeansOfType(ExitCodeGenerator.class).values());
            exitCode = getExitCode(generators);
        } finally {
            close(context);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        exitCode = (exitCode == 0 ? 1 : exitCode);
    }
    return exitCode;
}

From source file:org.springframework.hateoas.config.EnableHypermediaSupportIntegrationTest.java

private static void assertEntityLinksSetUp(ApplicationContext context) {

    Map<String, EntityLinks> discoverers = context.getBeansOfType(EntityLinks.class);
    assertThat(discoverers.values(), Matchers.<EntityLinks>hasItem(instanceOf(DelegatingEntityLinks.class)));
}

From source file:org.springframework.hateoas.config.EnableHypermediaSupportIntegrationTest.java

private static void assertRelProvidersSetUp(ApplicationContext context) {

    Map<String, RelProvider> discoverers = context.getBeansOfType(RelProvider.class);
    assertThat(discoverers.values(), Matchers.<RelProvider>hasItem(instanceOf(DelegatingRelProvider.class)));
}

From source file:org.springframework.integration.config.IdGeneratorConfigurer.java

private boolean setIdGenerator(ApplicationContext context) {
    try {// w  w  w.j  a v a  2  s  .  c o m
        IdGenerator idGeneratorBean = context.getBean(IdGenerator.class);
        if (logger.isDebugEnabled()) {
            logger.debug("using custom MessageHeaders.IdGenerator [" + idGeneratorBean.getClass() + "]");
        }
        Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator");
        ReflectionUtils.makeAccessible(idGeneratorField);
        IdGenerator currentIdGenerator = (IdGenerator) ReflectionUtils.getField(idGeneratorField, null);
        if (currentIdGenerator != null) {
            if (currentIdGenerator.equals(idGeneratorBean)) {
                // same instance is already set, nothing needs to be done
                return false;
            } else {
                if (IdGeneratorConfigurer.theIdGenerator.getClass() == idGeneratorBean.getClass()) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Another instance of " + idGeneratorBean.getClass()
                                + " has already been established; ignoring");
                    }
                    return true;
                } else {
                    // different instance has been set, not legal
                    throw new BeanDefinitionStoreException(
                            "'MessageHeaders.idGenerator' has already been set and can not be set again");
                }
            }
        }
        if (logger.isInfoEnabled()) {
            logger.info("Message IDs will be generated using custom IdGenerator [" + idGeneratorBean.getClass()
                    + "]");
        }
        ReflectionUtils.setField(idGeneratorField, null, idGeneratorBean);
        IdGeneratorConfigurer.theIdGenerator = idGeneratorBean;
    } catch (NoSuchBeanDefinitionException e) {
        // No custom IdGenerator. We will use the default.
        int idBeans = context.getBeansOfType(IdGenerator.class).size();
        if (idBeans > 1 && logger.isWarnEnabled()) {
            logger.warn("Found too many 'IdGenerator' beans (" + idBeans + ") "
                    + "Will use the existing UUID strategy.");
        } else if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate MessageHeaders.IdGenerator. Will use the existing UUID strategy.");
        }
        return false;
    } catch (IllegalStateException e) {
        // thrown from ReflectionUtils
        if (logger.isWarnEnabled()) {
            logger.warn("Unexpected exception occurred while accessing idGenerator of MessageHeaders."
                    + " Will use the existing UUID strategy.", e);
        }
        return false;
    }
    return true;
}

From source file:org.springframework.integration.samples.zip.SpringIntegrationUtils.java

/**
 * Helper Method to dynamically determine and display input and output
 * directories as defined in the Spring Integration context.
 *
 * @param context Spring Application Context
 *//*from w  w w .  j  a  v  a 2s  .  co m*/
public static void displayDirectories(final ApplicationContext context) {

    final Map<String, FileReadingMessageSource> fileReadingMessageSources = context
            .getBeansOfType(FileReadingMessageSource.class);

    final List<String> inputDirectories = new ArrayList<String>();

    for (FileReadingMessageSource source : fileReadingMessageSources.values()) {
        final File inDir = (File) new DirectFieldAccessor(source).getPropertyValue("directory");
        inputDirectories.add(inDir.getAbsolutePath());
    }

    final Map<String, FileWritingMessageHandler> fileWritingMessageHandlers = context
            .getBeansOfType(FileWritingMessageHandler.class);

    final List<String> outputDirectories = new ArrayList<String>();

    for (final FileWritingMessageHandler messageHandler : fileWritingMessageHandlers.values()) {
        final Expression outDir = (Expression) new DirectFieldAccessor(messageHandler)
                .getPropertyValue("destinationDirectoryExpression");
        outputDirectories.add(outDir.getExpressionString());
    }

    final StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.append("\n=========================================================");
    stringBuilder.append("\n");

    for (final String inputDirectory : inputDirectories) {
        stringBuilder.append("\n    Intput directory is: '" + inputDirectory + "'");
    }

    for (final String outputDirectory : outputDirectories) {
        stringBuilder.append("\n    Output directory is: '" + outputDirectory + "'");
    }

    stringBuilder.append("\n\n=========================================================");

    logger.info(stringBuilder.toString());

}

From source file:org.springframework.web.reactive.resource.ResourceUrlProvider.java

private void detectResourceHandlers(ApplicationContext context) {
    logger.debug("Looking for resource handler mappings");

    Map<String, SimpleUrlHandlerMapping> beans = context.getBeansOfType(SimpleUrlHandlerMapping.class);
    List<SimpleUrlHandlerMapping> mappings = new ArrayList<>(beans.values());
    AnnotationAwareOrderComparator.sort(mappings);

    mappings.forEach(mapping -> {//from  w  w w  . j  a  v  a2  s.  c  om
        mapping.getHandlerMap().forEach((pattern, handler) -> {
            if (handler instanceof ResourceWebHandler) {
                ResourceWebHandler resourceHandler = (ResourceWebHandler) handler;
                if (logger.isDebugEnabled()) {
                    logger.debug("Found resource handler mapping: URL pattern=\"" + pattern + "\", "
                            + "locations=" + resourceHandler.getLocations() + ", " + "resolvers="
                            + resourceHandler.getResourceResolvers());
                }
                this.handlerMap.put(pattern, resourceHandler);
            }
        });
    });
}