Example usage for org.springframework.context.support ClassPathXmlApplicationContext getBean

List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext getBean

Introduction

In this page you can find the example usage for org.springframework.context.support ClassPathXmlApplicationContext getBean.

Prototype

@Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException 

Source Link

Usage

From source file:nz.co.jsrsolutions.ds3.DataScraper3.java

public static void main(String[] args) {

    logger.info("Starting application [ ds3 ] ...");

    ClassPathXmlApplicationContext context = null;

    try {/*from w ww.j  ava  2  s  . c  o m*/

        CommandLineParser parser = new GnuParser();

        CommandLine commandLine = parser.parse(CommandLineOptions.Options, args);

        if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) {

            StringBuffer environment = new StringBuffer();
            environment.append(SPRING_CONFIG_PREFIX);
            environment.append(commandLine.getOptionValue(CommandLineOptions.ENVIRONMENT));
            environment.append(SPRING_CONFIG_SUFFIX);

            context = new ClassPathXmlApplicationContext(environment.toString());
            context.registerShutdownHook();

            if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) {

                Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class);
                scheduler.start();

                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }

            } else {
                DataScraper3Controller controller = context.getBean(CONTROLLER_BEAN_ID,
                        DataScraper3Controller.class);
                controller.executeCommandLine(commandLine);
            }

        } else {

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("ds3", CommandLineOptions.Options);

        }

    } catch (DataScraper3Exception ds3e) {
        logger.error("Failed to execute command", ds3e);
    } catch (ParseException pe) {

        logger.error("Failed to parse command line", pe);

    } catch (Exception e) {

        logger.error("Failed to execute command", e);

    } finally {
        if (context != null) {
            context.close();
        }
    }

    logger.info("Exiting application [ ds3 ] ...");

}

From source file:com.rytis.oot2.AppXMLConfig.java

public static void run(String[] args) throws Throwable {
    SpringApplication.run(AppXMLConfig.class, args);
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("configuration.xml");

    Device device;/*from   w  ww .ja v a2 s .  c o  m*/
    device = applicationContext.getBean("device1", Device.class);
    device.Boot();
    device = applicationContext.getBean("device2", Device.class);
    device.Boot();
    device = applicationContext.getBean("device3", Device.class);
    device.Boot();
    device = applicationContext.getBean("device4", Device.class);
    device.Boot();
    device = applicationContext.getBean("device5", Device.class);
    device.Boot();
    device = applicationContext.getBean("device6", Device.class);
    device.Boot();
    device = applicationContext.getBean("device7", Device.class);
    device.Boot();
    device = applicationContext.getBean("device8", Device.class);
    device.Boot();

    ((AbstractApplicationContext) applicationContext).close();
}

From source file:com.sap.data.db.dao.HibernateUtil.java

private static Configuration configuration(String firstLoad) {
    Configuration configuration = threadLocal.get();
    if (null == configuration || "x".equalsIgnoreCase(firstLoad)) {
        if ("true".equals(PropertyUtil.getWebApplication())) {
            WebApplicationContext webAppCtx = ContextLoader.getCurrentWebApplicationContext();
            LocalSessionFactoryBean sfb = (LocalSessionFactoryBean) webAppCtx.getBean("&sessionFactory",
                    LocalSessionFactoryBean.class);
            configuration = sfb.getConfiguration();
        } else {/*w  ww. j  a va 2  s. co m*/
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                    PropertyUtil.getSpringAppContext());
            LocalSessionFactoryBean localSessionFactoryBean = context.getBean("&sessionFactory",
                    LocalSessionFactoryBean.class);
            configuration = localSessionFactoryBean.getConfiguration();
        }
    }
    threadLocal.set(configuration);
    return configuration;
}

From source file:net.itransformers.idiscover.v2.core.Main.java

public static void main1(String[] args) {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("discovery.xml",
            "connectionsDetails.xml");
    NetworkNodeDiscovererImpl nodeDiscovererImpl = applicationContext.getBean("discovery",
            NetworkNodeDiscovererImpl.class);
    ConnectionDetails connectionDetails = new ConnectionDetails();
    connectionDetails.setConnectionType("SNMP");
    connectionDetails.put("ipAddress", "172.16.13.3");
    connectionDetails.put("version", "1");
    connectionDetails.put("community-ro", "netTransformer-r");
    connectionDetails.put("community-rw", "netTransformer-rw");
    connectionDetails.put("timeout", "3500");
    connectionDetails.put("retries", "3");
    connectionDetails.put("port", "161");
    connectionDetails.put("max-repetitions", "65535");
    connectionDetails.put("mibDir", "snmptoolkit/mibs");
    int depth = 10;
    NetworkDiscoveryResult result = nodeDiscovererImpl.discoverNetwork(Arrays.asList(connectionDetails), depth);

    System.out.println(result);//from   w ww. ja  va2s. c o  m
}

From source file:eu.trentorise.smartcampus.ac.provider.repository.persistence.AcDaoPersistenceImplTest.java

@BeforeClass
public static void setup() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/config.xml");
    dao = ctx.getBean("acPersistenceDao", AcDao.class);
    serviceImpl = ctx.getBean(TXAcProviderService.class);
}

From source file:com.spvp.dal.MySqlDatabase.java

public static MySqlDatabase getInstance() {

    if (db == null) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        db = ctx.getBean("mysqlDb", MySqlDatabase.class);
    }//from  w  w w. j  av  a 2s. c o m
    return db;
}

From source file:org.geowebcache.blobstore.memory.distributed.HazelcastCacheProviderTest.java

@BeforeClass
public static void initialSetup() {
    // Creating an Hazelcast configuration
    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(APP_CONTEXT_FILENAME);

    // Create a nullblobstore to add to the memory blobstore
    NullBlobStore nbs = new NullBlobStore();

    mem1 = new MemoryBlobStore();
    mem1.setStore(nbs);// w w w.j  av  a 2  s.  c o m
    mem1.setCacheBeanName(CACHE_1_NAME);
    mem1.setApplicationContext(appContext);

    mem2 = new MemoryBlobStore();
    mem2.setStore(nbs);
    mem2.setCacheBeanName(CACHE_2_NAME);
    mem2.setApplicationContext(appContext);

    // Get the two Hazelcast Cache instances
    cache1 = appContext.getBean(CACHE_1_NAME, HazelcastCacheProvider.class);
    cache2 = appContext.getBean(CACHE_2_NAME, HazelcastCacheProvider.class);

    // Ensure both the caches are available and immutable
    assertTrue(cache1.isAvailable());
    assertTrue(cache1.isImmutable());
    assertTrue(cache2.isAvailable());
    assertTrue(cache2.isImmutable());
}

From source file:net.siegmar.japtproxy.JaptProxyServer.java

/**
 * Starts Jetty.//from   www . j  a v a 2  s . c o m
 *
 * @param host        the host to bound.
 * @param port        the port to bound.
 * @param contextPath the context path to bound.
 */
private static void startServer(final String host, final int port, final String contextPath) {
    final Logger log = LoggerFactory.getLogger(JaptProxyServer.class);
    log.info("Starting Japt-Proxy {} on host {} port {} using context path '{}'", Util.VERSION,
            StringUtils.defaultIfEmpty(host, "*"), port, contextPath);

    // Spring startup
    final ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
            "master.xml", "standalone.xml");
    classPathXmlApplicationContext.registerShutdownHook();

    // Jetty startup
    final Server server = new Server();

    final Connector connector = new BlockingChannelConnector();

    if (!StringUtils.isBlank(host)) {
        connector.setHost(host);
    }

    connector.setPort(port);
    server.setConnectors(new Connector[] { connector });

    server.setStopAtShutdown(true);

    final Context root = new Context(server, contextPath);
    final JaptProxyServlet japtProxyServlet = classPathXmlApplicationContext.getBean("japtProxyServlet",
            JaptProxyServlet.class);
    root.addServlet(new ServletHolder(japtProxyServlet), "/*");

    try {
        server.start();
    } catch (final Exception e) {
        // shame on Jetty's exception handling
        throw new IllegalStateException("Couldn't start HTTP engine", e);
    }
}

From source file:pl.touk.hades.sql.timemonitoring.HadesSpringContextIT.java

@Test
public void shouldLoadSpringContextForHost1() throws SchedulerException, InterruptedException {

    ClassPathXmlApplicationContext ctx;

    ctx = new ClassPathXmlApplicationContext("/integration/context.xml");
    ctx.getBean("scheduler", Scheduler.class).start();

    String cronAlfa = "1 2 3 * * ?";
    String cronBeta = "2 3 4 * * ?";
    StringFactory.beansByName.put("cronAlfa", cronAlfa);
    StringFactory.beansByName.put("cronBeta", cronBeta);

    assertEquals(cronAlfa, ctx.getBean("monitorAlfa", SqlTimeBasedQuartzMonitor.class).getCron());
    assertEquals(cronBeta, ctx.getBean("monitorBeta", SqlTimeBasedQuartzMonitor.class).getCron());

    ctx.getBean("scheduler", Scheduler.class).shutdown();
    ctx.close();//from   w w  w  .j a  v a2 s  . com
}

From source file:org.lottery.common.message.ProducerTest.java

@Test
public void testSend() {
    final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONFIG);
    ctx.start();/*from  ww w .j  a  va2 s. c om*/

    final MessageChannel channel = ctx.getBean("common-message.producer", MessageChannel.class);

    channel.send(MessageBuilder.withPayload("from messageChannel" + System.currentTimeMillis())
            .setHeader("messageKey", "key").setHeader("topic", "test").build());

    MessageProducer messageProducer = ctx.getBean(MessageProducer.class);
    messageProducer.send("test", "from messageProducer" + System.currentTimeMillis());
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    ctx.close();
}