Example usage for org.springframework.context ApplicationContext getBean

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

Introduction

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

Prototype

<T> T getBean(String name, Class<T> requiredType) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

From source file:com.malsolo.mongodb.humongous.main.Main.java

public static void main(String... args) {

    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);

    MongoOperations ops = context.getBean("mongoTemplate", MongoOperations.class);

    //Create article
    /*//  ww w. j  a  v  a 2 s .c  o  m
    Article article = new Article();
    article.setAuthorId(UUID.randomUUID());
    article.setAuthor("Javier");
    article.setDate(new Date());
    article.setTitle("Ttulo");
            
    //Inserts
    ops.insert(article);
    */

    //Find one article
    Article article = ops.findOne(query(where("author").is("Javier")), Article.class);

    System.out.println(article);

    ArticleRepository articleRepository = context.getBean("articleRepository", ArticleRepository.class);
    article = articleRepository.findByAuthor("Javier");

    System.out.println(article);

    Comment comment = new Comment();
    comment.setAuthor("David el Gnomo");
    comment.setDate(new Date());
    comment.setText("Another comment");

    ops.upsert(query(where("author").is("Javier")), new Update().push("comments", comment), Article.class);

}

From source file:com.amazonaws.services.simpleworkflow.flow.examples.deployment.DeploymentInitiator.java

/**
 * @param args/*from   w ww .  j  a v a2s . c o m*/
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    URL pUrl = DeploymentHost.class
            .getResource("/com/amazonaws/services/simpleworkflow/flow/examples/log4j.properties");
    PropertyConfigurator.configure(pUrl);

    ApplicationContext appContext = new ClassPathXmlApplicationContext(
            "/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentInitiator-context.xml");

    DeploymentWorkflowClientExternalFactory workflowFactory = appContext.getBean("workflowFactory",
            DeploymentWorkflowClientExternalFactory.class);

    String applicationStackConfigFile = args[0];
    // Use applicationStackConfig as workflowId to prohibit running multiple deployments of the same stack in parallel
    String workflowId = new File(applicationStackConfigFile).getName();
    DeploymentWorkflowClientExternal worklfowClient = workflowFactory.getClient(workflowId);
    String template = loadFile(applicationStackConfigFile);
    worklfowClient.deploy(template);
    System.out.println("Initiated deployment from " + applicationStackConfigFile);
}

From source file:com.reversemind.glia.other.spring.GliaServerSpringContextLoader.java

public static void main(String... args) throws InterruptedException {

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "META-INF/hypergate-server-context.xml");

    ServerFactory.Builder builderAdvertiser = applicationContext.getBean("serverBuilderAdvertiser",
            ServerFactory.Builder.class);

    LOG.debug("--------------------------------------------------------");
    LOG.debug("Builder properties:");
    LOG.debug("Name:" + builderAdvertiser.getName());
    LOG.debug("Instance Name:" + builderAdvertiser.getInstanceName());
    LOG.debug("port:" + builderAdvertiser.getPort());
    LOG.debug("isAutoSelectPort:" + builderAdvertiser.isAutoSelectPort());

    LOG.debug("Type:" + builderAdvertiser.getType());

    LOG.debug("Zookeeper connection string:" + builderAdvertiser.getZookeeperHosts());
    LOG.debug("Zookeeper base path:" + builderAdvertiser.getServiceBasePath());

    IHyperGateServer server = builderAdvertiser.build();

    LOG.debug("\n\n");
    LOG.debug("--------------------------------------------------------");
    LOG.debug("After server initialization - properties");
    LOG.debug("\n");
    LOG.debug("Server properties:");
    LOG.debug("......");
    LOG.debug("Name:" + server.getName());
    LOG.debug("Instance Name:" + server.getInstanceName());
    LOG.debug("port:" + server.getPort());

    server.start();//from w  w  w .j  a va 2s.  co  m

    Thread.sleep(60000);

    server.shutdown();

    ServerFactory.Builder builderSimple = (ServerFactory.Builder) applicationContext
            .getBean("serverBuilderSimple");
    LOG.debug("" + builderSimple.port());

    IHyperGateServer serverSimple = builderSimple.setAutoSelectPort(true).setName("N A M E").setPort(8000)
            .setPayloadWorker(new IPayloadProcessor() {
                @Override
                public Map<Class, Class> getPojoMap() {
                    return null;
                }

                @Override
                public void setPojoMap(Map<Class, Class> map) {
                }

                @Override
                public void setEjbMap(Map<Class, String> map) {
                }

                @Override
                public void registerPOJO(Class interfaceClass, Class pojoClass) {
                }

                @Override
                public Payload process(Object payloadObject) {
                    return null;
                }
            }).build();

    LOG.debug("\n\n");
    LOG.debug("--------------------------------------------------------");
    LOG.debug("Simple Glia server");
    LOG.debug("\n");
    LOG.debug("Server properties:");
    LOG.debug("......");
    LOG.debug("Name:" + serverSimple.getName());
    LOG.debug("Instance Name:" + serverSimple.getInstanceName());
    LOG.debug("port:" + serverSimple.getPort());

}

From source file:bankconsoleapp.console.Main.java

/**
 * @param args the command line arguments
 *///from w w w .  j  a v a  2s . c o  m
public static void main(String[] args) {

    //Injecting applicationContext to main
    ApplicationContext context = new ClassPathXmlApplicationContext("bankconsoleapp/applicationContext.xml");

    EmployeeService eS = context.getBean("EmployeeService", EmployeeService.class);
    CustomerService cS = context.getBean("CustomerService", CustomerService.class);
    SavingService sS = context.getBean("SavingService", SavingService.class);

    String userName, pass;
    Scanner in = new Scanner(System.in);
    boolean user = false;
    boolean savingRedo = false;

    do {

        System.out.println("Enter Employee ID:");
        userName = in.nextLine();
        for (Employee emp : eS.getAllEmp()) {
            if (userName.equals(emp.geteID())) {
                System.out.println("Password:");
                pass = in.nextLine();
                for (Employee em : eS.getAllEmp()) {
                    if (pass.equals(em.getPassword())) {

                        user = true;
                    }
                }
            }
        }

    } while (!user);

    long start = System.currentTimeMillis();
    long end = start + 60 * 1000; // 60 seconds * 1000 ms/sec
    int operation = 0;
    int userChoice;

    boolean quit = false;
    do {
        System.out.println("ACME Bank Saving System:");
        System.out.println("------------------------");
        System.out.println("1. Create Customer & Saving Account");
        System.out.println("2. Deposit Money");
        System.out.println("3. Withdraw Money");
        System.out.println("4. View Balance");
        System.out.println("5. Quit");
        System.out.print("Operation count: " + operation + "(Shut down at 5)");
        userChoice = in.nextInt();
        switch (userChoice) {
        case 1:

            //create customer, then saving account regard to existing customer( maximum 2 SA per Customer)
            System.out.println("Create Customer :");
            String FirstN, LastN, DoB, accNum, answer;

            Scanner sc = new Scanner(System.in);
            Customer c = new Customer();
            int saID = 0;

            System.out.println("Enter First Name:");
            FirstN = sc.nextLine();
            c.setFname(FirstN);
            System.out.println("Enter Last Name:");
            LastN = sc.nextLine();
            c.setLname(LastN);
            System.out.println("Enter Date of Birth:");
            DoB = sc.nextLine();
            c.setDoB(DoB);

            do {

                System.out.println("Creating saving acount, Enter Account Number:");
                accNum = sc.nextLine();
                c.setSA(accNum);
                c.setSavingAccounts(c.getSA());
                saID++;
                System.out.println("Create another SA? Y/N?");
                answer = sc.nextLine();
                if (answer.equals("n")) {
                    savingRedo = true;
                }
                if (saID == 2) {
                    System.out.println("Maximum Saving account reached!");
                }
            } while (!savingRedo && saID != 2);

            cS.createCustomer(c);
            operation++;

            break;
        case 2:
            // deposit

            String acNum;
            int amt;
            Scanner sc1 = new Scanner(System.in);
            System.out.println("Enter Saving Account number u wish to do deposit.");
            acNum = sc1.nextLine();
            System.out.println("Enter amount :");
            amt = sc1.nextInt();

            sS.deposit(acNum, amt);
            operation++;

            break;
        case 3:
            String acNums;
            int amts;
            Scanner sc2 = new Scanner(System.in);
            System.out.println("Enter Saving Account number u wish to do withdraw.");
            acNums = sc2.nextLine();
            System.out.println("Enter amount :");
            amts = sc2.nextInt();

            sS.withdraw(acNums, amts);
            operation++;
            break;

        case 4:
            // view
            System.out.println("Saving Account Balance:");
            System.out.println(sS.getAllSA());
            operation++;
            break;

        case 5:
            quit = true;
            break;
        default:
            System.out.println("Wrong choice.");
            break;
        }
        System.out.println();
        if (operation == 5) {
            System.out.println("5 operation reached, System shutdown.");
        }
        if (System.currentTimeMillis() > end) {
            System.out.println("Session Expired.");
        }
    } while (!quit && operation != 5 && System.currentTimeMillis() < end);
    System.out.println("Bye!");

}

From source file:to.sparks.mtgox.example.TradingBot.java

public static void main(String[] args) throws Exception {

    ApplicationContext context = new ClassPathXmlApplicationContext("to/sparks/mtgox/example/TradingBot.xml");
    TradingBot me = context.getBean("tradingBot", TradingBot.class);
}

From source file:org.springone2gx_2011.integration.enricher.EnricherDemo.java

/**
 * @param args//from  w  ww  .jav a  2s .c o  m
 */
public static void main(String[] args) {

    ApplicationContext context = new ClassPathXmlApplicationContext("enricher-config.xml", EnricherDemo.class);
    Company original = new Company();
    original.setName("VMWare");
    original.setTicker("VMW");
    System.out.println("Sending company: " + original);
    Message<?> request = MessageBuilder.withPayload(original).build();
    context.getBean("inputChannel", MessageChannel.class).send(request);
}

From source file:org.sonews.Application.java

/**
 * The main entrypoint./*from   ww w  . j a  v a 2s .c om*/
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    System.out.println(VERSION);
    Thread.currentThread().setName("Mainthread");

    // Command line arguments
    boolean async = false;
    boolean feed = false; // Enable feeding?
    boolean purger = false; // Enable message purging?
    int port = -1;

    for (int n = 0; n < args.length; n++) {
        switch (args[n]) {
        case "-async": {
            async = true;
            break;
        }
        case "-c":
        case "-config": {
            Config.inst().set(Config.LEVEL_CLI, Config.CONFIGFILE, args[++n]);
            System.out.println("Using config file " + args[n]);
            break;
        }
        case "-C":
        case "-context": {
            // FIXME: Additional context files
            n++;
            break;
        }
        case "-dumpjdbcdriver": {
            System.out.println("Available JDBC drivers:");
            Enumeration<Driver> drvs = DriverManager.getDrivers();
            while (drvs.hasMoreElements()) {
                System.out.println(drvs.nextElement());
            }
            return;
        }
        case "-feed": {
            feed = true;
            break;
        }
        case "-h":
        case "-help": {
            printArguments();
            return;
        }
        case "-p": {
            port = Integer.parseInt(args[++n]);
            break;
        }
        case "-plugin-storage": {
            System.out.println("Warning: -plugin-storage is not implemented!");
            break;
        }
        case "-purger": {
            purger = true;
            break;
        }
        case "-v":
        case "-version":
            // Simply return as the version info is already printed above
            return;
        }
    }

    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
    context = new FileSystemXmlApplicationContext(new String[] { "sonews.xml" }, context);

    // Enable storage backend
    StorageProvider sprov = context.getBean("storageProvider", StorageProvider.class);
    StorageManager.enableProvider(sprov);

    ChannelLineBuffers.allocateDirect();

    // Add shutdown hook
    Runtime.getRuntime().addShutdownHook(new ShutdownHook());

    // Start the listening daemon
    if (port <= 0) {
        port = Config.inst().get(Config.PORT, 119);
    }

    NNTPDaemon daemon = context.getBean(NNTPDaemon.class);
    daemon.setPort(port);
    daemon.start();

    // Start Connections purger thread...
    Connections.getInstance().start();

    // Start feeds
    if (feed) {
        FeedManager.startFeeding();
    }

    if (purger) {
        Purger purgerDaemon = new Purger();
        purgerDaemon.start();
    }

    // Wait for main thread to exit (setDaemon(false))
    daemon.join();
}

From source file:org.another.logserver.Starter.java

/**
 *
 * @param args/*from  w w  w.j av  a 2  s. c  o  m*/
 */
public static void main(String[] args) {

    LOGGER.info("Starting Another Log server ...");

    // Initialize components

    LOGGER.debug("Starting Spring context ...");
    final ApplicationContext springContext = new ClassPathXmlApplicationContext("spring.xml");

    LOGGER.info("Spring intilization: {}", springContext.getStartupDate());

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            super.run();
            LOGGER.debug("Running Shutdown Hook");

            Configurator conf = springContext.getBean("configurator", Configurator.class);
            for (IEndPoint ep : conf.getConfiguredEndPoints().values()) {
                ep.stop();
            }

        }

    });

    ((AbstractApplicationContext) springContext).registerShutdownHook();

    LOGGER.debug("Entering wait loop");
    try {
        while (true) {
            Thread.sleep(1000 * 60 * 60);
        }
    } catch (Exception e) {
        LOGGER.error("", e);
    }

}

From source file:com.albert.javatest.JavaTestExample.java

public static void main(String args[]) {
    String cfg = "com/albert/si/gateway/context.xml";
    ApplicationContext context = new ClassPathXmlApplicationContext(cfg);
    try {//ww  w .j a  va 2s .com
        HelloService helloService = context.getBean("helloGateway", HelloService.class);
        System.out.println("Printing in HelloWorldExample by helloGateway: " + helloService.sayHello("World"));
    } finally {
        ((ConfigurableApplicationContext) context).close();
    }
}

From source file:exercise1.BlogConsole.java

protected static BlogService createBlogService() {
    // Use ApplicationContext to enable container-managed
    // transactions.
    ApplicationContext context = new ClassPathXmlApplicationContext("exercise1/applicationContext.xml");
    return context.getBean("blogService", BlogService.class);
}