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:com.joshlong.examples.data.counter.Main.java

public static void main(String[] args) throws Throwable {
    ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/counter.xml");
    Map<String, Counter> counters = ac.getBeansOfType(Counter.class);
    for (String beanName : counters.keySet())
        exercise(beanName, counters.get(beanName));
}

From source file:org.apache.s4.adapter.Adapter.java

public static void main(String args[]) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//from   www . j  a v  a 2s. c  o  m
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    options.addOption(OptionBuilder.withArgName("userconfig").hasArg()
            .withDescription("user-defined legacy data adapter configuration file").create("d"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    String userConfigFilename = null;
    if (commandLine.hasOption("d")) {
        userConfigFilename = commandLine.getOptionValue("d");
    }

    File userConfigFile = new File(userConfigFilename);
    if (!userConfigFile.isFile()) {
        System.err.println("Bad user configuration file: " + userConfigFilename);
        System.exit(1);
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = configBase + File.separatorChar + "adapter-conf.xml";
    File configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("adapter config file %s does not exist\n", configPath);
        System.exit(1);
    }

    // load adapter config xml
    ApplicationContext coreContext;
    coreContext = new FileSystemXmlApplicationContext("file:" + configPath);
    ApplicationContext context = coreContext;

    Adapter adapter = (Adapter) context.getBean("adapter");

    ApplicationContext appContext = new FileSystemXmlApplicationContext(
            new String[] { "file:" + userConfigFilename }, context);
    Map listenerBeanMap = appContext.getBeansOfType(EventProducer.class);
    if (listenerBeanMap.size() == 0) {
        System.err.println("No user-defined listener beans");
        System.exit(1);
    }
    EventProducer[] eventListeners = new EventProducer[listenerBeanMap.size()];

    int index = 0;
    for (Iterator it = listenerBeanMap.keySet().iterator(); it.hasNext(); index++) {
        String beanName = (String) it.next();
        System.out.println("Adding producer " + beanName);
        eventListeners[index] = (EventProducer) listenerBeanMap.get(beanName);
    }

    adapter.setEventListeners(eventListeners);
}

From source file:jmona.driver.Main.java

/**
 * Run the {@link EvolutionContext#stepGeneration()} method until the
 * CompletionConditionon is met, executing any Processors after each
 * generation step./*from  w  w  w . j a  va2s.  c om*/
 * 
 * Provide the location of the Spring XML configuration file by using the
 * <em>--config</em> command line option, followed by the location of the
 * configuration file. By default, this program will look for a configuration
 * file at <code>./context.xml</code>.
 * 
 * @param args
 *          The command-line arguments to this program.
 */
@SuppressWarnings("unchecked")
public static void main(final String[] args) {
    // set up the list of options which the parser accepts
    setUpParser();

    // get the options from the command line arguments
    final OptionSet options = PARSER.parse(args);

    // get the location of the XML configuration file
    final String configFile = (String) options.valueOf(OPT_CONFIG_FILE);

    // create an application context from the specified XML configuration file
    final ApplicationContext applicationContext = new FileSystemXmlApplicationContext(configFile);

    // get the evolution contexts, completion criteria, and processors
    @SuppressWarnings("rawtypes")
    final Map<String, EvolutionContext> evolutionContextsMap = applicationContext
            .getBeansOfType(EvolutionContext.class);
    @SuppressWarnings("rawtypes")
    final Map<String, CompletionCondition> completionCriteriaMap = applicationContext
            .getBeansOfType(CompletionCondition.class);
    @SuppressWarnings("rawtypes")
    final Map<String, Processor> processorMap = applicationContext.getBeansOfType(Processor.class);

    // assert that there is only one evolution context bean in the app. context
    if (evolutionContextsMap.size() != 1) {
        throw new RuntimeException("Application context contains " + evolutionContextsMap.size()
                + " EvolutionContext beans, but must contain only 1.");
    }

    // assert that there is only one completion criteria bean in the app context
    if (completionCriteriaMap.size() != 1) {
        throw new RuntimeException("Application context contains " + completionCriteriaMap.size()
                + "CompletionCondition beans, but must contain only 1.");
    }

    // get the evolution context and completion condition from their maps
    @SuppressWarnings("rawtypes")
    final EvolutionContext evolutionContext = MapUtils.firstValue(evolutionContextsMap);
    @SuppressWarnings("rawtypes")
    final CompletionCondition completionCondition = MapUtils.firstValue(completionCriteriaMap);

    try {
        // while the criteria has not been satisfied, create the next generation
        while (!completionCondition.execute(evolutionContext)) {
            // create the next generation in the evolution
            evolutionContext.stepGeneration();

            // perform all post-processing on the evolution context
            for (@SuppressWarnings("rawtypes")
            final Processor processor : processorMap.values()) {
                processor.process(evolutionContext);
            }
        }
    } catch (final CompletionException exception) {
        throw new RuntimeException(exception);
    } catch (final EvolutionException exception) {
        throw new RuntimeException(exception);
    } catch (final ProcessingException exception) {
        throw new RuntimeException(exception);
    }
}

From source file:org.apache.s4.client.Adapter.java

@SuppressWarnings("static-access")
public static void main(String args[]) throws IOException, InterruptedException {

    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//from   ww w.j  a va  2 s . com
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    options.addOption(OptionBuilder.withArgName("userconfig").hasArg()
            .withDescription("user-defined legacy data adapter configuration file").create("d"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    String userConfigFilename = null;
    if (commandLine.hasOption("d")) {
        userConfigFilename = commandLine.getOptionValue("d");
    }

    File userConfigFile = new File(userConfigFilename);
    if (!userConfigFile.isFile()) {
        System.err.println("Bad user configuration file: " + userConfigFilename);
        System.exit(1);
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = configBase + File.separatorChar + "client-adapter-conf.xml";
    File configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("adapter config file %s does not exist\n", configPath);
        System.exit(1);
    }

    // load adapter config xml
    ApplicationContext coreContext;
    coreContext = new FileSystemXmlApplicationContext("file:" + configPath);
    ApplicationContext context = coreContext;

    Adapter adapter = (Adapter) context.getBean("client_adapter");

    ApplicationContext appContext = new FileSystemXmlApplicationContext(
            new String[] { "file:" + userConfigFilename }, context);

    Map<?, ?> inputStubBeanMap = appContext.getBeansOfType(InputStub.class);
    Map<?, ?> outputStubBeanMap = appContext.getBeansOfType(OutputStub.class);

    if (inputStubBeanMap.size() == 0 && outputStubBeanMap.size() == 0) {
        System.err.println("No user-defined input/output stub beans");
        System.exit(1);
    }

    ArrayList<InputStub> inputStubs = new ArrayList<InputStub>(inputStubBeanMap.size());
    ArrayList<OutputStub> outputStubs = new ArrayList<OutputStub>(outputStubBeanMap.size());

    // add all input stubs
    for (Map.Entry<?, ?> e : inputStubBeanMap.entrySet()) {
        String beanName = (String) e.getKey();
        System.out.println("Adding InputStub " + beanName);
        inputStubs.add((InputStub) e.getValue());
    }

    // add all output stubs
    for (Map.Entry<?, ?> e : outputStubBeanMap.entrySet()) {
        String beanName = (String) e.getKey();
        System.out.println("Adding OutputStub " + beanName);
        outputStubs.add((OutputStub) e.getValue());
    }

    adapter.setInputStubs(inputStubs);
    adapter.setOutputStubs(outputStubs);

}

From source file:org.xmatthew.spy2servers.core.context.ComponentContextUtils.java

@SuppressWarnings("unchecked")
public static ComponentContext getComponentContext(ApplicationContext context) {
    Map beansMap = context.getBeansOfType(Component.class);
    if (beansMap != null) {

        List<Component> components = new ArrayList<Component>(beansMap.size());
        components.addAll(beansMap.values());
        ComponentContext componentContext = new ComponentContext();
        componentContext.setComponents(components);
        return componentContext;
    }/*from   w w  w  . j  a v a  2 s  . c o m*/
    return null;
}

From source file:org.opensprout.osaf.util.ApplicationContextUtils.java

public static <T> T getBeanByType(ApplicationContext applicationContext, Class<T> clazz) {
    Map beanMap = applicationContext.getBeansOfType(clazz);
    int size = beanMap.size();
    if (size == 0) {
        if (applicationContext.getParent() != null)
            return getBeanByType(applicationContext.getParent(), clazz);
        throw new NoSuchBeanDefinitionException(clazz.getSimpleName());
    }// w ww.j  a va2  s.co  m
    if (size > 1)
        throw new NoSuchBeanDefinitionException(
                "No unique bean definition type [" + clazz.getSimpleName() + "]");
    return (T) beanMap.values().iterator().next();
}

From source file:com.excilys.ebi.spring.dbunit.utils.ApplicationContextUtils.java

public static <T> T getOptionalUniqueBeanOfType(ApplicationContext applicationContext, Class<T> type) {
    Map<String, T> configs = applicationContext.getBeansOfType(type);

    isTrue(configs.size() <= 1, "found more than one bean in the applicationContext");

    return configs.size() == 1 ? configs.values().iterator().next() : null;
}

From source file:tomekkup.helenos.context.PostConfiguringClusterListener.java

public static void propagadeConfigChanges(ApplicationContext applicationContext, Cluster cluster) {
    Map<String, ClusterConfigAware> beans = applicationContext.getBeansOfType(ClusterConfigAware.class);
    for (ClusterConfigAware bean : beans.values()) {
        bean.setNewCluster(cluster);/*w  w  w  .  j  av  a2 s  .c o m*/
    }
}

From source file:demo.vmware.commands.CommandRegionUtils.java

/**
 * this is an argument for making this a singleton bean instead of static. We cold then make this
 * ApplicationContextAware/*from   ww w.  ja v  a 2  s  .c om*/
 * 
 * @param mainContext
 * @return
 */
public static Map<String, GemfireTemplate> getAllGemfireTemplates(ApplicationContext mainContext) {
    Map<String, GemfireTemplate> allRegionTemplates = mainContext.getBeansOfType(GemfireTemplate.class);
    return allRegionTemplates;
}

From source file:org.activiti.spring.SpringConfigurationHelper.java

public static ProcessEngine buildProcessEngine(URL resource) {
    log.debug(// w w  w.  j  av  a2s  .c  o m
            "==== BUILDING SPRING APPLICATION CONTEXT AND PROCESS ENGINE =========================================");

    ApplicationContext applicationContext = new GenericXmlApplicationContext(new UrlResource(resource));
    Map<String, ProcessEngine> beansOfType = applicationContext.getBeansOfType(ProcessEngine.class);
    if ((beansOfType == null) || (beansOfType.isEmpty())) {
        throw new ActivitiException("no " + ProcessEngine.class.getName()
                + " defined in the application context " + resource.toString());
    }

    ProcessEngine processEngine = beansOfType.values().iterator().next();

    log.debug(
            "==== SPRING PROCESS ENGINE CREATED ==================================================================");
    return processEngine;
}