Example usage for org.springframework.context ConfigurableApplicationContext getBean

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

Introduction

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

Prototype

Object getBean(String name) throws BeansException;

Source Link

Document

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

Usage

From source file:com.vitco.Main.java

public static void main(String[] args) throws Exception {
    // display version number on splash screen
    final SplashScreen splash = SplashScreen.getSplashScreen();
    if (splash != null) {
        Graphics2D g = splash.createGraphics();
        if (g != null) {
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            Font font = Font
                    .createFont(Font.TRUETYPE_FONT,
                            new SaveResourceLoader("resource/font/arcade.ttf").asInputStream())
                    .deriveFont(Font.PLAIN, 42f);
            g.setFont(font);/*from w  w  w  .ja v a  2  s.c  o m*/
            //g.setFont(g.getFont().deriveFont(9f));
            g.setColor(VitcoSettings.SPLASH_SCREEN_OVERLAY_TEXT_COLOR);
            int width = g.getFontMetrics().stringWidth(VitcoSettings.VERSION_ID);
            g.drawString(VitcoSettings.VERSION_ID, 400 - 20 - width, 110);
            splash.update();
            g.dispose();
        }
    }

    // the JIDE license
    SaveResourceLoader saveResourceLoader = new SaveResourceLoader("resource/jidelicense.txt");
    if (!saveResourceLoader.error) {
        String[] jidelicense = saveResourceLoader.asLines();
        if (jidelicense.length == 3) {
            com.jidesoft.utils.Lm.verifyLicense(jidelicense[0], jidelicense[1], jidelicense[2]);
        }
    }

    // check if we are in debug mode
    if ((args.length > 0) && args[0].equals("debug")) {
        ErrorHandler.setDebugMode();
        debug = true;
    }

    // build the application
    final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "com/vitco/glue/config.xml");

    // for debugging
    if (debug) {
        ((ActionManager) context.getBean("ActionManager")).performValidityCheck();
        ((ComplexActionManager) context.getBean("ComplexActionManager")).performValidityCheck();
    }

    // open vsd file when program is started with "open with"
    MainMenuLogic mainMenuLogic = ((MainMenuLogic) context.getBean("MainMenuLogic"));
    for (String arg : args) {
        if (arg.endsWith(".vsd")) {
            File file = new File(arg);
            if (file.exists() && !file.isDirectory()) {
                mainMenuLogic.openFile(file);
                break;
            }
        }
    }

    // perform shortcut check
    ((ShortcutManager) context.getBean("ShortcutManager")).doSanityCheck(debug);
    //        // test console
    //        final Console console = ((Console) context.getBean("Console"));
    //        new Thread() {
    //            public void run() {
    //                while (true) {
    //                    console.addLine("text");
    //                    try {
    //                        sleep(2000);
    //                    } catch (InterruptedException e) {
    //                       //e.printStackTrace();
    //                    }
    //                }
    //            }
    //        }.start();

    // add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            // make reference so Preferences object doesn't get destroyed
            Preferences pref = ((Preferences) context.getBean("Preferences"));
            // trigger @PreDestroy
            context.close();
            // store the preferences (this needs to be done here, b/c
            // some PreDestroys are used to store preferences!)
            pref.save();
        }
    });
}

From source file:com.javiermoreno.springboot.rest.App.java

public static void main(String[] args) {
    ConfigurableApplicationContext context = new SpringApplicationBuilder().showBanner(true).sources(App.class)
            .run(args);/*from   ww w  .  ja  va2  s  .c o m*/
    context.addApplicationListener(new ApplicationPidListener());

    GestionPersonasService service = context.getBean(GestionPersonasService.class);
    service.registrarNuevaPersona(new Persona("11111111A", "Karl", "Marx"));
}

From source file:com.geas.blog.blog.App.java

License:asdf

public static void main(String[] args) {

    System.out.println("load context");
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Post testPost = new Post();
    testPost.setPostId(1);/*from   w w w.  j  av a2s .c  o m*/
    testPost.setTitle("John");
    testPost.setBody("l;asdfja;lsdkfj;ladsfj;l;ldkskfja;sldfkja;lsdfjaf;lfdjkas;dlfja;ldsfkja;dlfk");
    PostDBService testPostService = (PostDBService) context.getBean("postService");
    testPostService.persistPost(testPost);
    System.out.println("Updated title :" + testPostService.findPostById(1).getTitle());
    testPost.setTitle("Hello");
    testPostService.updatePost(testPost);
    System.out.println("Updated title :" + testPostService.findPostById(1).getTitle());
    testPostService.deletePost(testPost);
    context.close();
}

From source file:com.hillert.botanic.MainApp.java

/**
 * Main class initializes the Spring Application Context and populates seed
 * data using {@link SeedDataService}.//w  ww. j av  a2s .  com
 *
 * @param args Not used.
 */
public static void main(String[] args) {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put("redisPort", SocketUtils.findAvailableTcpPort());

    SpringApplication app = new SpringApplication(MainApp.class);
    app.setDefaultProperties(props);

    ConfigurableApplicationContext context = app.run(args);

    MapPropertySource propertySource = new MapPropertySource("ports", props);

    context.getEnvironment().getPropertySources().addFirst(propertySource);

    SeedDataService seedDataService = context.getBean(SeedDataService.class);
    seedDataService.populateSeedData();
}

From source file:com.clicktravel.cheddar.server.rest.application.RestApplication.java

/**
 * Starts the RestServer to listen on the given port and address combination
 *
 * @param args String arguments, {@code [context [service-port [status-port [bind-address] ] ] ]} where
 *            <ul>/*w ww.j  ava 2s .c  o m*/
 *            <li>{@code context} - Name of application, defaults to {@code UNKNOWN}</li>
 *            <li>{@code service-port} - Port number for REST service endpoints, defaults to {@code 8080}</li>
 *            <li>{@code status-port} - Port number for REST status endpoints ({@code /status} and
 *            {@code /status/healthCheck}), defaults to {@code service-port + 100}</li>
 *            <li>{@code bind-address} - Local IP address to bind server to, defaults to {@code 0.0.0.0}</li>
 *            </ul>
 *
 * @throws Exception
 */
public static void main(final String... args) {
    final String context = args.length > 0 ? args[0] : "UNKNOWN";
    final int servicePort = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
    final int statusPort = args.length > 2 ? Integer.parseInt(args[2]) : servicePort + 100;
    final String bindAddress = args.length > 3 ? args[3] : "0.0.0.0";
    MDC.put("context", context);
    MDC.put("hostId", System.getProperty("host.id", "UNKNOWN"));
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    final Logger logger = LoggerFactory.getLogger(RestApplication.class);
    try {
        logger.info("Java process starting");
        logger.debug(String.format("java.version:[%s] java.vendor:[%s]", System.getProperty("java.version"),
                System.getProperty("java.vendor")));
        @SuppressWarnings("resource")
        final ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        logger.debug("Finished getting ApplicationContext");
        final ApplicationLifecycleController applicationLifecycleController = applicationContext
                .getBean(ApplicationLifecycleController.class);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("Shutdown hook invoked - Commencing graceful termination of Java process");
            applicationLifecycleController.shutdownApplication();
            logger.info("Java process terminating");
        }));
        applicationLifecycleController.startApplication(servicePort, statusPort, bindAddress);
        Thread.currentThread().join();
    } catch (final InterruptedException e) {
        logger.info("Java process interrupted");
        System.exit(1);
    } catch (final Exception e) {
        logger.error("Error starting Java process", e);
        System.exit(1);
    }
}

From source file:com.github.bfour.fpliteraturecollector.application.Application.java

public static void main(String[] args) {

    try {/*from   w  ww  .  j  av  a2 s.c o m*/

        // https://vvirlan.wordpress.com/2014/12/10/solved-caused-by-java-awt-headlessexception-when-trying-to-create-a-swingawt-frame-from-spring-boot/
        SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
        builder.headless(false);
        ConfigurableApplicationContext context = builder.run(args);

        // Neo4jResource myBean = context.getBean(Neo4jResource.class);
        // myBean.functionThatUsesTheRepo();

        // ServiceManager servMan = ServiceManager
        // .getInstance(ServiceManagerMode.TEST);
        ServiceManager servMan = context.getBean(ServiceManager.class);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(servMan,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);

        FPJGUIManager.getInstance().initialize();

        MainWindow.getInstance(servMan).setVisible(true);

    } catch (BeanCreationException e) {
        e.printStackTrace();
        if (ExceptionUtils.getRootCause(e) instanceof IOException)
            ApplicationErrorDialogue.showMessage("Sorry, could not access the database.\n"
                    + "This might be because it is currently in use or because there are insufficient access rights.\n"
                    + "Try closing all running instances of this application and restart.");
        else
            ApplicationErrorDialogue.showDefaultMessage(e, BUG_REPORT_URL);
    } catch (Exception e) {
        e.printStackTrace();
        ApplicationErrorDialogue.showDefaultMessage(e, BUG_REPORT_URL);
    }

}

From source file:io.fabric8.quickstarts.activemq.App.java

public static void main(String[] args) {
    // Clean out any ActiveMQ data from a previous run
    FileSystemUtils.deleteRecursively(new File("activemq-data"));

    // Launch the application
    ConfigurableApplicationContext context = SpringApplication.run(App.class, args);

    // Send a message
    MessageCreator messageCreator = new MessageCreator() {
        @Override/*ww w .j a  v a 2  s .  c  om*/
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage("<hello>world!</hello>");
        }
    };
    JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
    System.out.println("Sending a new message.");
    jmsTemplate.send(destination, messageCreator);
}

From source file:mk.finki.ranggo.aggregator.Aggregator.java

public static void main(String[] args) {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:spring/application-config.xml");

    //make sure alchemyapi.key hold your license key
    final String alchemyapi_key = context.getBeanFactory().resolveEmbeddedValue("${alchemyapi.key}");

    PersonRepository personRepository = context.getBean(PersonRepository.class);
    ContentRepository contentRepository = context.getBean(ContentRepository.class);

    ContentsAggregator aggregator = new ContentsAggregatorImpl(alchemyapi_key, personRepository,
            contentRepository);//from ww  w. j  a  va 2 s. c  om

    //populates the data store with the test dataset
    Aggregator.test(aggregator);

    //executes update method
    Aggregator.update(null, aggregator);

    context.close();
}

From source file:com.all.uberpeer.Uberpeer.java

public static void main(String[] args) {
    ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            new String[] { "/applicationContext.xml" });
    Uberpeer uberpeer = applicationContext.getBean(Uberpeer.class);
    uberpeer.start();// www.  j  ava2  s .  c  o  m
}

From source file:ar.com.zauber.labs.kraken.providers.wikipedia.apps.administrative.MainAdministrative.java

/**
 * Lee la pagina // w ww  .  j a v a  2 s  .c o m
 * http://es.wikipedia.org/wiki/Departamentos_y_partidos_de_la_Argentina
 * la tabla de localidades
 */
public static void main(final String[] args)
        throws IOException, JAXBException, SAXException, URISyntaxException {
    final ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
            "ar/com/zauber/labs/kraken/providers/wikipedia/apps/administrative/"
                    + "config/context-administrative-kraken-spring.xml");
    ctx.registerShutdownHook();

    new ArgentinaDepartmentsSync(
            new BufferedReader(new InputStreamReader(
                    ArgentinaDepartmentsSync.class.getResourceAsStream("es.txt"), "utf-8")),
            (WikiPageRetriever) ctx.getBean("httpWikiPageRetriever"), LangUtils.ES,
            (Closure) ctx.getBean("administrativeClosure"));
}